Here is my code for file uploading in PHP. All the things seems at place but file is not getting added into the selected folder. The destination folder is stored in the same folder, where .php file is stored. Please help !!!
<form action="" method="post" enctype="multipart/form-data">
Select Image File to Upload:
<p><input type="file" name="file"/></p>
<p><input type="submit" name="upload" value="Upload"/></p>
</form>
I will take the same example
<!DOCTYPE html>
<html>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
in your case you are missing attribute value of action
File : upload.php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
?>
I have also share the link with you were you can use different type of validation on file uploads
https://www.w3schools.com/php/php_file_upload.asp
Related
I am using summernote rich text editor, and I want to edit my posted data(stored in DB). I am sending the value to the text area and inputs but not showing into the text area and showing into the input. kindly share some solutions and suggestions with me. any jquery and js function like this...
here is rendered data to web page
route.get('/edit/:id', async (req, res) =>{
const id = req.params.id
const article = await Article.findById(id)
res.render('editarticle',{article:article})
})
and here is ejs or HTML
<%- include('header'); -%>
<div class="container-9">
<h2>Create Article Here</h2>
<hr>
<form action="/create/blog" method='post'>
<input type="text" name="title" id="" placeholder="Enter Title" value='<%=article.title%>'/>
<input type="text" name="description" id="dics" placeholder="Enter Description" value='<%=article.discription%>'/>
<hr>
<button id='btn-post' type="submit">Post</button>
<textarea name='content' id="body" rows="10" value="<%=article.content%>" ></textarea>
</form>
</div>
<%- include('footer'); -%>
I have solved this problem with help of one line of code. I have got the solution after 2 month
var value = $('#value').val()
console.log(value);
$('textarea#body').summernote('pasteHTML', value);
if want to render the HTML for edit this will work, var value = $('#value').val() it just receiving the value (HTML) from the backend and $('textarea#body').summernote('pasteHTML', value); this line of code pesting the HTML into summernote editor.
#tushar Very useful !!
I use it on summer note as like
Put Content in a div, and set it display none
<div id="contentDumpDiv" style="display:none;">
<?php echo $post['content'] ?>
</div>
then use this javascript code
var value = $('#contentDumpDiv').html();
$('textarea#saContent').summernote('pasteHTML', value);
I have an angular form with text fields and want to add am option for uploading image in the same form. I'm stuck with the latter.
The angular form contains html tag to upload the file. Once the file is uploaded the uploaded file's name is displayed in the input field.
<!--blog.html-->
<!--form to create new blog-->
<form #blogForm="ngForm" (ngSubmit)="Save(blogForm);">
<div class="form-group">
<label>Blog Title</label>
<input type="text" class="form-control input-text" maxlength="45" name="title" ngModel #blogtitle="ngModel" required placeholder="Blog Title">
<span class="required" *ngIf="blogtitle.errors?.required && (blogtitle.dirty||blogtitle.touched||blogtitle.untouched)">*required</span>
</div>
<div class="form-group">
<label>Blog </label>
<textarea class="textarea form-control" maxlength="150" name="summary" [(ngModel)]="summary">
Blog</textarea>
</div>
<div class="form-group">
<label>Blog Desc</label>
<textarea class="textarea form-control" name="description" ngModel #blogdescription="ngModel" required>Blog Description</textarea>
<span class="required" *ngIf="blogdescription.errors?.required && (blogdescription.dirty||blogdescription.touched||blogdescription.untouched)">*required</span>
</div>
<div class="form-group">
<label>HashTags</label>
<input type="text" class="form-control input-text" name="hashtag" [(ngModel)]="hashtag" placeholder="hashtags">
</div>
<div class="form-group">
<div class="custom-file">
<!--file upload -->
<input type="file" class="custom-file-input form-control-lg" name="file" id="customFile"
value="imageFile.name" (change)="handleImageFileInput($event)">
<input type="text" readonly="true" [value]="imageFile" class="custom-file-label" >
<button type="button" (click)="upload()">Upload</button>
</div>
</div>
<input type="button" class="btn-default" (click)="Save(blogForm)" value="Create">
</form>
//blog.ts
//function to create new blog
Save(blogForm: any) {
if (blogForm.valid === true) {
blogForm = blogForm.value;
blogForm.userId = this.user_id;
blogForm.author = this.display_name;
window.confirm('Want to Publish?');
this.blogservice.Save(blogForm).subscribe(response => {
window.alert('Blog published successfully');
this.router.navigate(['/dashboard']);
});
}
}
//function to display selected image in the input field
handleImageFileInput(event) {
const img1 =event.target.files[0];
const img =event.target.files[0].name;
const fileList: FileList = event.target.files;
const fileCount = fileList.length;
if (fileCount > 0) {
const file = fileList.item(0);
console.log(` image file: ${file.name}`);
console.log(img1);
if(img == undefined) {
this.imageFile = 'Upload an image';
} else {
this.imageFile = img;
}
}
}
Need to save file along with form submission
Here's a JavaScript script which will read your data from input and display it :
<input type='file' accept='image/*' onchange='openFile(event)'><br>
<img id='output'>
<script>
var openFile = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var dataURL = reader.result;
var output = document.getElementById('output');
output.src = dataURL;
};
reader.readAsDataURL(input.files[0]);
};
</script>
It come from the documentation of FileReader.
With that you should be able to store the input wherever you want and store the path inside of your MongoDB collection.
Else if you want to use Angular plugins, here's one that could be useful for you :
angular-file-upload
I am developing a plugin, where I am using bootstrap nav tabs function to display different forms on selecting menu . I want to use nonce function . Should I give seperate nonce function for every form or same nonce for all the forms as they are on the same page. Pls guide.?
Each form should have its own nonce, even those forms are on the same page.
If the form is present in admin pages then we should use check_admin_referer function to verify the nonce.
example:
<html>
<div>
<form id="form1"method="post" action="">
<input type="text" name="something" value=""/>
<?php wp_nonce_field('some_form','some_form_nonce');?>
<input type ="hidden" name="form_name" value ="1"/>
<input type="submit" name="submit"/>
</div>
<div>
<form id="form2"method="post" action="">
<input type="text" name="someother" value=""/>
<?php wp_nonce_field('some_other','some_other_nonce');?>
<input type ="hidden" name="form_name" value ="2"/>
<input type="submit" name="submit"/>
</div>
</html>
after that on processing page you should add the code like this
<?php
if(!isset($_POST['form_name'])){
if($_POST['form_name']==1){
if ( ! empty( $_POST ) && check_admin_referer( 'some_form', 'some_form_nonce' ) ) {
// process form1 data
}else if($_POST['form_name']=2){
if ( ! empty( $_POST ) && check_admin_referer( 'some_other', 'some_other_nonce' ) ) {
// process form2 data
}
}
?>
This code I tried in my app and is working as I expected...
I Put the Database Search for my Plugin.
But When Searching gives 404 Error !
What do I do to fix 404 Error?
My Code is:
<?php
function qrn_search_code(){
global $wpdb,$table_prefix;
if($_POST['submit']) {
if($_POST['search']) {
$search = $wpdb->get_results("SELECT ID, code FROM ".$table_prefix."qrn_dessini WHERE code LIKE '%".$_POST['search']."%' ORDER BY ID DESC;");
print_r($search);
}
}
<form method="POST" id="searchform">
<input type="text" name="name" class="qr_search" placeholder="جستجوی کد محصول ...">
<input type="submit" name="submit" value="Search" class="qr_submit">
</form>
}
add_shortcode('search_code','qrn_search_code');
?>
Thanks
I notice you have a beginning php tag at the end of your function, and also no ending:
<?php
}
add_shortcode('mysearch','search_code');
So I would try to change this to start:
}
<?php
add_shortcode('mysearch','search_code');
?>
1.jinja2 template file:
<!DOCTYPE html>
<html>
<head>
<title>image upload demo</title>
</head>
<body>
<form action="{{ imgup_url }}" method="post" accept-charset="utf-8"
enctype="multipart/form-data">
<input type=hidden id="token" value="{{ token }}">
<label for="filename">File:</label>
<input id="pictitle" name="pictitle" type="text" value="okkk" />
<input id="upfile" name="upfile" type="file" value="" />
<input id="button" type="submit" value="upload" />
</form>
</body>
</html>
2.views.py file
#view_config(permission='post', route_name='imgup',
renderer='shootout:jinja2/imgup.jinja2',
check_csrf=False)
def ueditor_ImgUp(request):
""" upload image """
form = Form(request, schema=ImgUpSchema)
token1 = request.session.new_csrf_token()
if 'form.submitted' in request.params:
token2 = request.session.get_csrf_token()
if token2 != request.POST['csrf_token']:
raise ValueError('CSRF token did not match')
print "imgup is login begin!!!"
source_pictitle = request.POST.get('pictitle')
source_filename = request.POST['upfile'].filename
response = Response()
myresponse = __myuploadfile(fileObj, source_pictitle, source_filename, 'pic')
response.write(myresponse)
print "imgup is success!!!"
return response
else:
return {'imgup_url':'/imgup','token':token1}
3.__init__.py file :
engine = engine_from_config(settings, 'sqlalchemy.')
DBSession.configure(bind=engine)
session_factory = UnencryptedCookieSessionFactoryConfig(
settings['session.secret']
)
authn_policy = SessionAuthenticationPolicy()
authz_policy = ACLAuthorizationPolicy()
config = Configurator(
settings=settings,
root_factory=RootFactory,
authentication_policy=authn_policy,
authorization_policy=authz_policy,
session_factory=session_factory
)
config.add_static_view('static', 'shootout:static')
config.add_static_view('html', 'shootout:html')
config.include(addroutes)
config.add_route('imgup','/imgup')
when submitted upload button show:
403 Forbidden
Access was denied to this resource.
CSRF token is missing or invalid
How to solve this problem?Thanks.
pyramid html post method need csrf_token,so i do:
view:
csrf_token = request.session.get_csrf_token()
return {'csrf_token':csrf_token}
template(Jinja2):
<input id="_csrf" type="hidden" value="{{ csrf_token }}"/>
success~