i working on plugin that has in back-end to add url of of site or post and short description and in front end show then in a widget,i have button for small image of post to be uploaded but it didi't work out but same code work fine in normal php...
$upload_errors = array(
// http://www.php.net/manual/en/features.file-upload.errors.php
UPLOAD_ERR_OK => "No errors.",
UPLOAD_ERR_INI_SIZE => "Larger than upload_max_filesize.",
UPLOAD_ERR_FORM_SIZE => "Larger than form MAX_FILE_SIZE.",
UPLOAD_ERR_PARTIAL => "Partial upload.",
UPLOAD_ERR_NO_FILE => "No file.",
UPLOAD_ERR_NO_TMP_DIR => "No temporary directory.",
UPLOAD_ERR_CANT_WRITE => "Can't write to disk.",
UPLOAD_ERR_EXTENSION => "File upload stopped by extension."
);
// process the form data
$tmp_file = $_FILES['file_upload']['tmp_name'];
$target_file = basename($_FILES['file_upload']['name']);
$upload_dir = "uploads";
// You will probably want to first use file_exists() to make sure
// there isn't already a file by the same name.
// move_uploaded_file will return false if $tmp_file is not a valid upload file
// or if it cannot be moved for any other reason
if(move_uploaded_file($tmp_file, $upload_dir."/".$target_file)) {
$message = "File uploaded successfully.";
} else {
$error = $_FILES['file_upload']['error'];
$message = $upload_errors[$error];
}
this is the form used to upload image
<form action='' method='post' name="text_form" onsubmit="return Blank_TextField_Validator()" enctype="multipart/form-data">
<table class='form-table'><tr valign='top'>
<th scope='row'><lable for='new_Directory_name'>Enter the Title:</lable></th>
<td><input type='text' id='newtextchange' name='newtextchange' size="100" /></br></td>
</tr>
<tr>
<th scope='row'><lable for='new_Directory_name'>Enter the Description:</lable></th>
<td><textarea rows="4" cols="50" name='textarea1'>
</textarea></br></td>
</tr>
<tr>
<th scope='row'><lable for='new_Directory_name'>Enter the URL:</lable></th>
<td><input type='text' id='newtextchange1' name='newtextchange1' size="100" /></br></td>
</tr>
<tr>
<th scope='row'><lable for='new_Directory_name'>Upload image:</lable></th>
<td> <input type="hidden" name="MAX_FILE_SIZE" value="1000000" /><input type="file" name="file_upload" /><br><br><input id='addtobow' class='button-secondary action' type='submit' value='Add to Best of web' name='submit'/></td>
</tr>
</table>
</form>
You should look at wp_handle_upload for this one.
The example given there is very usefull.
To save the url you can use the following lines:
$upload_overrides = array( 'test_form' => false );
$source = wp_handle_upload( $_FILES['file'], $upload_overrides );
if ( $source )
$input = serialize( $source );
Hope it helps!
problem is with the file upload url and this is how i fix it..,now it is working fine...
$tmp_file = $_FILES['file_upload']['tmp_name'];
$target_file = basename($_FILES['file_upload']['name']);
//$upload_dir = "D:\softwares_installed\wamp\www\wordpress\wp-content\plugins\bestofweb\uploads";
$upload_dir =ABSPATH . "wp-content/plugins/bestofweb/uploads";
$up_urlp1="/wp-content/plugins/bestofweb/uploads";
// You will probably want to first use file_exists() to make sure
// there isn't already a file by the same name.
// move_uploaded_file will return false if $tmp_file is not a valid upload file
// or if it cannot be moved for any other reason
if(move_uploaded_file($tmp_file, $upload_dir."/".$target_file)) {
//$message = "File uploaded successfully.";
//echo $upload_dir."/".$target_file;
//echo bloginfo('wpurl');
$up_url= $up_urlp1."/".$target_file;
//echo $up_url;
//if($message == "File uploaded successfully.")
// {
// $imgpath=$upload_dir.
// }
} else {
$error = $_FILES['file_upload']['error'];
// $message = $upload_errors[$error];
}
Related
I have an OROCRM application and there is a datagrid, needs to be extended with a column named by userNames, and intented to display data in a custom twig cell.
To maintain this i made a DataGridListener class and in it a method to extend columns:
/**
* Creates specific column names for selected persons
*
* #param Datagrid $datagrid
* #param array $persons
*
* #return array
*/
protected function addColumnsForPersons(Datagrid $datagrid, array $persons): array
{
$config = $datagrid->getConfig();
$additionalColumns = [];
foreach ($persons as $person) {
$column = [
'label' => $person->getName(),
'template' => 'MyBundle:Partials/Datagrid/Attendance:person_attendance.html.twig',
'type' => 'twig',
'frontend_type' => 'html',
'data_name' => 'person_' . $person->getId(),
'data' => 'person_' . $person->getId(),
'translatable' => false,
'editable' => false,
'align' => 'middle'
];
$config->addColumn('person_' . $person->getId(), $column);
$additionalColumns[] = 'person_' . $person->getId();
}
return $additionalColumns;
}
I add also data for person by the following:
$wrapperData = $datagrid->getData();
foreach($attendancesAtDay as $attendance) {
// This block can be changed to a workaround
$dayData['person_' . $attendance['personid']] = (object)([
'arrival' => Carbon::createFromFormat('Y-m-d G:i:s', $attendance['arrival'])->format('H:i'),
'leave' => Carbon::createFromFormat('Y-m-d G:i:s', $attendance['leave'])->format('H:i'),
'logins' => $attendance['logins'],
'worktime' => gmdate('H:i', $attendance['worktime'] * 60)
]);
}
$gridData[] = $dayData;
$wrapperData->setData($gridData);
The template is reachable and PHPStorm can follow its link from reference, and is the following:
<div>
<div style="width:40px">
{{ value.worktime }}
</div>
<div style="width:40px">
{{ value.arrival }}
</div>
<div style="width:40px">
{{ value.leave }}
</div>
<div style="width:40px">
{{ value.logins }}
</div>
</div>
With this method i got the columns named by person, but with empty data. With xdebug the code never goes into the template.
With some workaround if i change the block in the foreach it renders needed data.
The workaround is the following:
$dayData['person_' . $attendance['personid']] = sprintf(
'<table>
<tr>
<td>
Worktime
</td>
<td>
Arrival
</td>
<td>
Leave
</td>
<td>
Logins
</td>
</tr>
<tr>
<td>
%s
</td>
<td>
%s
</td>
<td>
%s
</td>
<td>
%s
</td>
</tr>
</table>',
gmdate('H:i', $attendance['worktime'] * 60),
Carbon::createFromFormat('Y-m-d G:i:s', $attendance['arrival'])->format('H:i'),
Carbon::createFromFormat('Y-m-d G:i:s', $attendance['leave'])->format('H:i'),
$attendance['logins']);
I tried to use array instead of object without success, or any error message in var/logs/dev.log .
I wanted to avoid this workaround, and wondering why don't throws error in case i added booth twig template to column and html code as data, and why doesn't runs into the cell template?
So what do i wrong?
Thanks for any help!
I am using phpexcel library with zend framwork.
I want to send mail to user with excel file attachment, all are working good but mail send with two attachment one is duplicate, i dont know why.
here is my function which is used to export excel and send it to user
public function exportandmail($name = NULL) {
if ($name === NULL) {
$name = 'excel_' . date('Y_m_d');
}
$name = $name.'.xlsx';
$objWriter = PHPExcel_IOFactory::createWriter($this->_excel, 'Excel2007');
$objWriter->save("public/uploads/Mailexcel/".$name);
$message="<table width='90%' align='center' >
<tr>
<th height='15' style='background-color:#037296;padding:10px;color:#FFFFFF' align='left'>excel</th>
</tr>
<tr>
<td style='padding:10px'><strong>Please find the attachment. </strong>
</td>
<tr>
<td style='padding:10px'>
Thanks,
</td>
</tr>
</table>";
$mail = new Zend_Mail();
$mail->setBodyHtml($message);
$mail->setFrom('sender#gmail.com', 'sender');
$mail->addTo('user#gmail.com');
$mail->setSubject('find attachment');
$fileContents = file_get_contents("public/uploads/Mailexcel/".$name);
$file = $mail->createAttachment($fileContents);
$file->filename = "excel.xlsx";
$mail->addAttachment($file);
$mail->send();
exit;
}
Thanks in advance.
I got the solution,
In my code, i use both createAttachment and addAttachment, thats why my mail send with duplicate attachment.
Remove addAttachment and its working fine.
$fileContents = file_get_contents("public/uploads/Mailexcel/".$name);
$file = $mail->createAttachment($fileContents);
$file->filename = "excel.xlsx";
$mail->addAttachment($file); // Remove this
$mail->send();
Currently, my site has a table in a database that contain user name and password. The front end has 2 textboxes and a login button. Once the user fills out those two fields and click login, it will check if user name and password is matched in the database, if so, let them in and set session variable to check through out the entier site. Is this secure enough? How do i convert this to form authentication? I don't want to throw out my login table. Can i still use it if i was to convert this to form authentication? Can anyone point me or show me how this could be done? Thanks
The standard login I use is somethig like this:
index.html:
<form action="login.php" method="post">
<table width="100%" border="0" style = "border-top: 2px solid #CCC; padding-top: 15px;">
<tr>
<td><input type="text" class="text_box" placeholder="Usuario" name="user" id="user"></td>
</tr>
<tr>
<td><input type="password" class="text_box" placeholder="ContraseƱa" name="pass" id="pass"></td>
</tr>
<tr>
<td>
<?php
show_message();
?>
<input type="submit" value="Ingresar" class="boton_submit">
</td>
</tr>
</table>
</form>
And the php...
<?php
if(isset($_POST["user"]) && isset($_POST["pass"])){
include('conect_to_database.php');
$user = $_POST["user"];
$pass = $_POST["pass"];
if(!filter_var($_POST["user"], FILTER_VALIDATE_EMAIL)) {
//Not a valid email ... sends back to login form
header( 'Location: index.php' ) ;
exit();
}
$query = "SELECT id FROM user where user = ? and pass = ? LIMIT 1";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $user, $pass);
$stmt->execute();
$stmt->bind_result($id);
while ($stmt->fetch()) {
//set your session variable
header( 'Location: ../../control_panel.php' ) ;
exit();
}
//echo invalid user... sends back to login form
header( 'Location: index.php' ) ;
}
?>
I would also recommend checking for special chars in both user and password.
Also, you should never store passwords in your database. You should just store a hash of the real password using special algorithms.
Wordpress Email Form
Hi all
I've been using this sort of email form in a number of sites and it's always worked.
I've tried to use it in a Wordpress site but it won't
Is there any obvious reason why this approach won't work in a Wordpress site.
I need an email form that doesn't reload the contact page as the form is at the bottom.
html
<form action="#" id="contact_form">
<input type="text" id="name" placeholder="Name:">
<input type="text" id="email" placeholder="Email:">
<textarea id="message" rows="8" cols="40" placeholder="Message:"></textarea>
<input type="submit" id="submit"/>
<div id="status">
<p></p>
</div>
</form>
Jquery
$('#submit').click(function(){
//
var nameVal = $('#contact_form #name').val();
var emailVal = $('#contact_form #email').val();
var messageVal = $('#contact_form #message').val();
//
$.post('/contact_form.php', {name: nameVal, email: emailVal, message: messageVal}, function(data){
$("#status p").html(data);
$("#status p").show().fadeOut(3500);
if(data.indexOf('Thank You')==0) {document.forms[0].reset();}
});
})
php
$errors = array();
$required_fields = array('name','email','message');
foreach($required_fields as $fieldname){
if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])){
$errors[] = $fieldname;
}
}
if(empty($errors)){
$name_field = Trim(stripslashes($_POST['name']));
$name = explode(' ', $name_field);
$firstname = ucfirst($name[0]);
$email_field = Trim(stripslashes($_POST['email']));
$message = Trim(stripslashes($_POST['message']));
//
$to = "info#ttmt.org.uk";
$subject = "Email from Website";
$body = "From: $name_field\n E-Mail: $email_field\n Message:\n $message";
//
mail($to, $subject, $body);
echo "Thank You $firstname";
}else{
echo "Please complete all.";
}
--- UPDATE ---
I've got part of it working now.
Part of the problem was the jquery couldn't find the php.
I created a 'code' folder inside wp-conntent and put the php there and the jquery looks like this.
$j.post('wp-content/code/contactEngine.php', { theName:nameVal, theEmail:emailVal, theMessage:messageVal }, function(data){
Now I'm getting the returned data form the php file but the email isn't sent.
Will this not work in WP
mail($to, $subject, $body);
You cannot use $_POST['name'] within Wordpress. Using other namings for input fields will fix your issue, eventually you could use the 'Contact Form 7' Wordpress-plugin for a better user experience :-)
I have two files the one which hosts my actual contact form and then a file where i post the form to.
contactform.php (which is part of the footer template)
<form id="contact" action="<?php bloginfo('template_url'); ?>/sendmail.php" method="post">
<label for="name">Your name: *</label>
<input type="text" id="nameinput" name="name" value=""/>
<label for="email">Your email: *</label>
<input type="text" id="emailinput" name="email" value=""/>
<label for="comment">Your message: *</label>
<textarea cols="20" rows="7" id="commentinput" name="comment"> </textarea><br />
</form>
sendmail.php
<?PHP
if(isset($_POST['submit'])) {
error_reporting(E_NOTICE);
function valid_email($str)
{
return ( ! preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*#([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
}
if($_POST['name']!='' && $_POST['email']!='' && valid_email($_POST['email'])==TRUE && strlen($_POST['comment'])>1)
{
$to = preg_replace("([\r\n])", "", hexstr($_POST['receiver']));
$from = preg_replace("([\r\n])", "", $_POST['email']);
$subject = "Website contact message from ".$_POST['name'];
$message = $_POST['comment'];
$match = "/(bcc:|cc:|content\-type:)/i";
if (preg_match($match, $to) ||
preg_match($match, $from) ||
preg_match($match, $message)) {
die("Header injection detected.");
}
$headers = "From: ".$from."\r\n";
$headers .= "Reply-to: ".$from."\r\n";
if(wp_mail($to, $subject, $message, $headers,'',true))
{
echo 1; //SUCCESS
}
else {
echo 2; //FAILURE - server failure
}
}
else {
echo 3; //FAILURE - not valid email
}
}else{
die("Direct access not allowed!");
}
function hexstr($hexstr) {
$hexstr = str_replace(' ', '', $hexstr);
$hexstr = str_replace('\x', '', $hexstr);
$retstr = pack('H*', $hexstr);
return $retstr;
}
?>
The issue is that this does not know of wp_mail function. I know that I need to include something so wp_mail will be available but what do I add? The function does exist. The issue with including the file that has wp_mail defined is that inside that function it requires some core php functions (wp_mail is being overwritten by cimy_swift plugin)
hi why not try just submitting the form to the base wpurl? then within your header.php file copy and paste your code in?
ie: using a hidden field you can check to see if its been posts, in this case the hidden field is called 'action' and it has a value of 'sendemail'.
form
<form id="contact" action="<?php bloginfo('wpurl'); ?>" method="post">
//form stuff
<input type="hidden" name="action" value="sendemail" />
</form>
Header.php
within the header file we do a call to check and see if the form has been posted,
<html>
<head>
<title><?php wp_title();?></title>
<?php
if( isset($_POST['action']) && ($_POST['action']=='sendemail') ) {
// run your code
}
?>
</head>
if you dont want to go down that route, and wish to use your theme folder to hold the php script then what to is, include the below in your sendmail.php file
define('WP_USE_THEMES', FALSE);
require('../../../wp-blog-header.php');
//above is assuming your file is located in the theme root, not a sub folder.
this will give you access to all the wordpress functions and shortcodes etc..etc..
hope that helps a little..
Marty