I am working on a form which is validated with jQuery before being submitted. One of the fields is a captcha.
The idea is very simple, the captcha is shown as an image and also stored in a hidden field. When the user enters the captcha in the input field it should be equal to the value of the hidden field. This is the jQuery code I have;
<script>
$(document).ready(function(){
$("#register").validate({
errorElement: 'div', ignore: 'hidden',
rules: {
password: {
required: true
},
password2: {
required: true, equalTo: "#password"
},
agree: {
required: true
},
captcha: {
required: true, equalTo: "#captcha2"
}
},
messages: {
password2: "Please repeat the same password",
captcha: "The captcha you entered is wrong",
agree: "You have to be at least 16 years old and agree to the terms of service"
}
});
});
</script>
The html code for the form is even simpler, but I will show only a part of it.
<p>
<img src='/includes/captcha.php' />
</p>
<p>
<label for="Captcha">Captcha</label>
<em> *</em><input type="text" name="captcha" id="captcha" size="25"
class="require" minlength="5" />
<input type="hidden" name="captcha2" id="captcha2"
value="<?php echo $_SESSION['captcha'];?>" />
<?php echo $_SESSION['captcha']; ?>
Here is something weird. When I echo the session['captcha'] I get a different value than the value in the hidden field. I get the previous captcha when I echo it.
So let's say the captcha value is ABC. When I refresh the page the captcha+hidden field change into DEF. But when I echo session['captcha'] I still get ABC.
Why is this happening?
Here is the code of the captcha.php file;
<?php
session_start();
header("Content-type: image/png");
$string = '';
for ($i = 0; $i < 5; $i++) {
// this numbers refer to numbers of the ascii table (lower case)
$string .= chr(rand(97, 122));
}
$_SESSION['captcha'] = $string;
putenv('GDFONTPATH=' . realpath('.'));
$dir = 'musicals';
$image = imagecreatetruecolor(170, 60);
$black = imagecolorallocate($image, 0, 0, 0);
$color = imagecolorallocate($image, 129, 180, 79); // green
$white = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image,0,0,399,99,$white);
imagettftext ($image, 30, 0, 10, 40, $color, $dir, $_SESSION['captcha']);
imagepng($image);
?>
The problem is that your captcha generation is within the image, and that this image is only accessed after the form has been accessed. Your captcha is generated AFTER you show the form, this is why it's always one step behind.
Aside from that, it's a bad idea to store the captcha solution in a hidden field. A person, or a bot, can simply parse the website's source code and extract and use it as the captcha solution.
Be sure that captcha.php is run before html code. It looks like captcha.php generates image and probably it is inserted as an img in HTML. Image is got after page loading (generating HTML) so captcha code in session is not regenerated.
I belive that you inserted hidden element with captcha as an example. It is bad idea to show captcha code as a hidden element in form.
Related
My jpg is 4kb, but when I upload it to the server, the PHP program writes it much larger, as 43kb, it's large and fuzzy, instead of being small and clear. How can I maintain the width and height? I've tried resizing after the photo is saved, but nothing happens. This is the code for the upload, and save.
<?php
// retrieve
echo "Request received";
$p= $_FILES["file"];
move_uploaded_file($p["tmp_name"], "pic3-1.jpg");
if ($p==nil) { echo "no photo"; }
// reply
$data = Array("Reply"=>"Imaged saved at server");
echo json_encode($data);
?>
Added to Xcode 8, Swift 3. The resolution is clear:
UIGraphicsBeginImageContext(CGSize(width:75, height: 75))
photo2.draw(in: CGRect(x: 0, y: 0, width: 75, height: 75))
photo=UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
i am developing a plugin where i have a backend-page which shows a input text-field and a button. When you click on that button, wordpress' media uploader opens and you can choose a file. The URL of that file will be inserted into that input fields value. Here you can see the code:
HTML:
<div class="wp-uploader">
<input id="upload_image" type="text" size="36" name="upload_image" value="" />
<input class="button" id="upload_image_button" type="button" value="Legg til PDF fra mediabibliotek" />
</div>
JQuery:
jQuery(document).ready(function($){
var custom_uploader;
$('#upload_image_button').click(function(e) {
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Velg en PDF',
button: {
text: 'Velg'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$('#upload_image').val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
});
I would like to achive that this chosen file will be sent as attachment of wp_mail.
Here is my function:
function dd_send_email(){
$email_sent = false;
// get email template data
$email_template_object = dd_get_current_options();
$url = $_POST['upload_image'];
$mail_attachment = array(WP_CONTENT_DIR=>$url);
// if email template data was found
if ( !empty( $email_template_object ) ):
// setup wp_mail headers
$wp_mail_headers = array('Content-Type: text/html; charset=UTF-8');
// use wp_mail to send email
$email_sent = wp_mail( array( 'example#email.com') , $email_template_object['dd_emne_forhaandsbestilling'], $email_template_object['dd_email_text_forhaandsbestilling'], $wp_mail_headers, $mail_attachment );
endif;
return $email_sent;
}
But this is not working. I still get emails without any attachment. I guess the way im getting the file-url is wrong but i couldn't find out how to do this.
Thanks for your help!
I did found the answer by myself. Because wp_mail needs the file path like this /uploads/2016/03/example.jpg we have to convert our url to a path like this.
I did achive this by changing the following in dd_send_mail() and thought i can share it with you:
// change url to path
$dd_url = $_POST['upload_image'];
$dd_path = parse_url($dd_url);
// cut the path to right directory
$array = explode("/norskeanalyser/wp-content", $dd_path['path']);
unset($array[0]);
$text = implode("/", $array);
and then i did save the $text into $mail_attachment and called it in wp_mail like above.
Thanks to everyone for great help!
I am new to web development and I am trying to put CAPTCHA into my website. I am stuck at this. And I couldn't find any help.
The following is my Form code:
<tr>
<td>
<img src="html-contact-form-captcha/captcha_code_file.php?rand=<?php echo rand(); ?>" id='captchaimg' ><br>
</td>
</tr>
<tr>
<td align="right"><b> Enter Image Text </b></td>
<td><input placeholder="Enter the code above here" id="6_letters_code" name="6_letters_code" type="text"><br>
<small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small>
</td>
</tr>
And on this same page I am trying to validate this CAPTCHA by the following code:
var cde = document.getElementById('6_letters_code');
if( cde.value == "" ||
($_SESSION['6_letters_code'] != $_POST['6_letters_code']) ) {
alert( "Code Matched!" );
//alert( "Code Doesn't Match! \n Code Not Entered!" );
return false;
}
And this is where I am getting my CAPTCHA: (captcha.php)
session_start(); // Staring Session
$captchanumber = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz'; // Initializing PHP variable with string
$captchanumber = substr(str_shuffle($captchanumber), 0, 6); // Getting first 6 word after shuffle.
$_SESSION["code"] = $captchanumber; // Initializing session variable with above generated sub-string
$image = imagecreatefromjpeg("bj.jpg"); // Generating CAPTCHA
$foreground = imagecolorallocate($image, 175, 199, 200); // Font Color
imagestring($image, 5, 45, 8, $captchanumber, $foreground);
header('Content-type: image/png');
imagepng($image);
Any help would be appreciated.
Thank you in advance.
In Javascript
If you want to evaluate that the captcha is correct in Javascript, which runs in your browser after the page was generated by PHP on the server, then Javascript will have to have the means to check it.
For this you have to use a session, in which you can store the captcha value. Use these steps:
At the start of the PHP file, that generates your form, you should select a captcha code. You store this in a session variable.
You produce a hash of the captcha in PHP and put it in a hidden field of the form. Give this field a proper id, so you can find it with Javascript.
$hash = sha1($captcha); // this is PHP code
Generate the image of the captcha, using the stored session variable.
Regrettably Javascript does not have any native hash algorithm. Other people have solved this:
http://caligatio.github.io/jsSHA/
So now you can also make a hash of the captcha, that was entered by the user into the form, in Javascript. All you need to do is to check it against the hash that PHP has put in the hidden field in the form. If they match the Captcha was correct.
As you can see, this is not really easy.
In PHP
It is easier to do the check in PHP after the form was submitted. I think I can assume your captcha.php works. In that you store $captchanumber in the session of the user. That was a good idea.
So you make the form, put the captcha in it, and let the user submit it. The check will now be done in PHP, like this:
$captchaNumber = $_SESSION['code'];
$userNumber = $_POST['6_letters_code']; // a name starting with number? eh??
if ($captchaNumber == $userNumber)
{
<.... the user did it correctly ....>
}
else
{
// it was the wrong code, back to the form
header('Location: '.<... url of form ...>);
}
The header() function should be used before any output. For starters I would suggest to submit the form to another PHP script. Once that works you can try an merge the form script and the submission script into one PHP script.
Please try the below code. I hope it work. I tried to write the code from scratch:-
<?php session_start();
// Staring Session
$im = imagecreate(90, 30);
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 0);
$captchaKey = substr(md5(time()), 0, 5);
$_SESSION["code"] = $captchaKey;
imagestring($im, 45, 20, 5, $captchaKey, $textcolor);
//header("Content-type: image/png");
$save = "captcha.png";
$x1 = imagepng($im, $save);
?>
<script>
function checkCaptcha() {
var cde = document.getElementById('6_letters_code');
if( cde.value == '<?php echo $_SESSION['code']; ?>
' ) {
alert( "Code Matched!" );
//alert( "Code Doesn't Match! \n Code Not Entered!" );
return false;
} else {
alert('Code not matched!')
}
}
</script>
<tr>
<td><img src="captcha.png" id='captchaimg' >
<br>
</td>
</tr>
<tr>
<td align="right"><b> Enter Image Text </b></td>
<td>
<input placeholder="Enter the code above here" id="6_letters_code" name="6_letters_code" type="text">
<br>
<button onclick="checkCaptcha()">
Click to check
</button><small>Can't read the image? click <a href='javascript: refreshCaptcha();'>here</a> to refresh</small></td>
</tr>
In my xampp htdocs folder I got two files: An image and a php script. I tried to create a word document with an image. This is the code I used:
$image = 'img.png';
$imageData = base64_encode(file_get_contents($image));
$src = 'data: '. mime_content_type($image).';base64,'.$imageData;
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=document_name.doc");
echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<h1>bla</h1>";
echo "<b>My first document</b>";
echo '<img src="',$src,'">';
echo "</body>";
echo "</html>";
Well actually I don't have Microsoft Word installed on my PC but it should work with Libre Office too. I also tried http://www.viewdocsonline.com but it didn't work. First I tried it with a way too big image and I thought that was causing the problem but it doesn't even work with a small image. The File is just loading all the time but can't be opened. The file size seems to be right - it's 52kb - so the image seems to be in the document.
But what could cause the error? How to find out and how to debug?
Word can't read Html, at least not if you specify the .doc extension.
You should use a Docx generator if you want to work with the latest version of Word (since 2007), or doc if you want to create a document readable from word 2003.
http://www.phpdocx.com/ works great for that (https://phpword.codeplex.com/ too, but isn't well supported)
Alright – with the help of edi9999 and his awesome library I was able to create a docx document with my text variables and my image.
Here is the code I used:
Javascript:
/*** importing all necessary scripts ***/
<script type="text/javascript" src="docxtemplater-master/libs/base64.js"></script>
<script type="text/javascript" src="docxtemplater-master/libs/jszip/jszip.js"></script>
<script type="text/javascript" src="docxtemplater-master/libs/jszip/jszip-load.js"></script>
<script type="text/javascript" src="docxtemplater-master/libs/jszip/jszip-inflate.js"></script>
<script type="text/javascript" src="docxtemplater-master/js/docxgen.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
/*** my JSON object with the variables for setTemplateVars() ***/
<script type="text/javascript">
var JSON = { "articles": [
{ "title": "test-title", "first_name": "Paul", "last_name": "Alan", "phone": "555-nose", "fileName": "abc" },
{ "title": "test-title2", "first_name": "John", "last_name": "Doe", "phone": "555-abcd", "fileName": "bcd" }
]
};
</script>
<script type="text/javascript">
var xhrDoc = new XMLHttpRequest();
xhrDoc.open('GET', 'Example.docx', true);
if (xhrDoc.overrideMimeType) {
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined');
}
xhrDoc.onreadystatechange = function (e) {
if (this.readyState == 4 && this.status == 200) {
window.docData = this.response;
}
};
xhrDoc.send();
var xhrImage = new XMLHttpRequest();
xhrImage.open('GET', 'dog.jpg', true);
if (xhrImage.overrideMimeType) {
xhrImage.overrideMimeType('text/plain; charset=x-user-defined');
}
xhrImage.onreadystatechange = function (e) {
if (this.readyState == 4 && this.status == 200) {
window.imgData = this.response;
}
};
xhrImage.send();
generateDoc = function (docData) {
var doc = new DocxGen(docData)
doc.setTemplateVars(
{ "first_name": JSON.articles[0]["first_name"],
"last_name": JSON.articles[0]["last_name"],
"phone": JSON.articles[0]["phone"],
"fileName": JSON.articles[0]["fileName"]
}
)
doc.applyTemplateVars()
imageList = doc.getImageList()
console.log(imageList);
doc.setImage(imageList[0].path, imgData);
doc.output()
}
</script>
HTML:
<button class="download_doc" onClick="generateDoc(window.docData)">download word docx with image</button>
Word template:
{phone}
Product name: {first_name}
Product reference : {last_name}
*in the middle is an image*
Blabla: {fileName}
*here is another image*
Well the content makes no sense of course but it works. But still there are some questions left (especially to edi9999 and I hope you could answer them for me please :) ):
1. The images has to be on the same server and you have to use a relative path, right? Link's didn't seem to work. I tried xhrImage.open('GET', 'http://link-to-an-image.com/image.jpg', true); but without success. Is it somehow possible to use external links to images?
2. There is an 304 error ("Not modified") in the console behind the GET Requests. Is that normal?
3. Does the image that shall replace the image in the word document have to be the same size (or at least the same aspect ratio) or are there any option variables that could make the replacement more flexible? For example: if I wanna have the image displayed over the full width in the word document and got a replacement image with a different aspect ratio, would it be possible to keep that aspect ratio and just increase the height of the image in the word document?
4. How to use more than one image for replacement? With xhrImage.open('GET', 'dog.jpg', true); only one image is opened. How to add more images to the "imageList" and how to determine the order?
5. The library is based on prototype and normally it's causing errors to use both (jQuery + Prototype) frameworks in one document. But I tried to use a jQuery function and it worked. Have you ever had any problems with using your library and jQuery in one document?
Found another solution:
With this library: https://github.com/PHPOffice/PHPWord
it's quite easy to create a docx file with formatted text and an image.
Here's the code that worked for me:
require_once('PHPWord-master/Classes/PHPWord.php');
$PHPWord = new PHPWord();
$section = $PHPWord->createSection();
$my_text='Hello world! I am formatted.';
$section->addText($my_text, array('name'=>'Tahoma', 'size'=>16, 'bold'=>true));
$section->addText(''); // adding some white space because the marginTop attribute of the image doesn't work
$filename="Jellyfish.jpg";
$size = getimagesize($filename);
$width="560"; //full width in a word document if image is 96dpi
$height=560/intval($size[0])*intval($size[1]);
$section->addImage(
$filename,
array(
'width' => $width,
'height' => $height,
'align' => 'center'
)
);
$section->addText('blabla');
$filename="dog.jpg";
$size = getimagesize($filename);
$height=560/intval($size[0])*intval($size[1]);
$section->addImage(
$filename,
array(
'width' => $width,
'height' => $height,
'align' => 'center'
)
);
$objWriter = PHPWord_IOFactory::createWriter($PHPWord, 'Word2007');
$objWriter->save('helloWorld.docx');
I am having a problem with a gd library issue. When I use the following code
<script type="text/javascript">
$.fn.infiniteCarousel = function () {
function repeat(str, num) {
return new Array( num + 1 ).join( str );
}
return this.each(function () {
var $wrapper = $('> div', this).css('overflow', 'hidden'),
$slider = $wrapper.find('> ul'),
$items = $slider.find('> li'),
$single = $items.filter(':first'),
singleWidth = $single.outerWidth(),
visible = Math.ceil($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border
currentPage = 1,
pages = Math.ceil($items.length / visible);
// 1. Pad so that 'visible' number will always be seen, otherwise create empty items
if (($items.length % visible) != 0) {
$slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
$items = $slider.find('> li');
}
// 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
$items.filter(':first').before($items.slice(- visible).clone().addClass('cloned'));
$items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
$items = $slider.find('> li'); // reselect
// 3. Set the left position to the first 'real' item
$wrapper.scrollLeft(singleWidth * visible);
// 4. paging function
function gotoPage(page) {
var dir = page < currentPage ? -1 : 1,
n = Math.abs(currentPage - page),
left = singleWidth * dir * visible * n;
$wrapper.filter(':not(:animated)').animate({
scrollLeft : '+=' + left
}, 500, function () {
if (page == 0) {
$wrapper.scrollLeft(singleWidth * visible * pages);
page = pages;
} else if (page > pages) {
$wrapper.scrollLeft(singleWidth * visible);
// reset back to start position
page = 1;
}
currentPage = page;
});
return false;
}
$wrapper.after('<a class="arrow back"><</a><a class="arrow forward">></a>');
// 5. Bind to the forward and back buttons
$('a.back', this).click(function () {
return gotoPage(currentPage - 1);
});
$('a.forward', this).click(function () {
return gotoPage(currentPage + 1);
});
// create a public interface to move to a specific page
$(this).bind('goto', function (event, page) {
gotoPage(page);
});
});
};
$(document).ready(function () {
$('.infiniteCarousel').infiniteCarousel();
$("a.pictureThumb").fancybox({
'autoScale' : true,
'autoDimension' : true,
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'speedIn' : 300,
'speedOut' : 200,
'hideOnOverlayClick' : true,
'hideOnContentClick': false
});
});
</script>
With this as the image generator, the only thing that comes out is what looks like programming code instead of an image. This script worked with a different scroller, but since I put this new scroller script (seen above), I am having problems with it generating an image (IE it just shows the loading icon), FireFox actually shows the programming code.
Here is the code that is making the call to the GD function:
<div class="infiniteCarousel">
<div class="wrapper">
<ul>
<?php
do { ?>
<li><a class="pictureThumb" href="picture.php?imgID=<?php $pieces = explode('_', $row_rsPictures['PictureFile']); echo $pieces[0]."_".$pieces[1]."_".$pieces[2]; if ($pieces[3] == "NN"){ echo "_NN_".$pieces[4]."_".$pieces[5];; } else { echo "_".$pieces[3]."_".$pieces[4]; } ?>&thumb=Y" title="<a href='addToCart.php?T=Pic?ID=<?php echo $row_rsPictures['PictureID']; ?>' target='_parent' style='color:#fe6d00' >Add This Image To Your Shopping Cart</a><br><?php echo $row_rsPictures['BoatName'];if($row_rsPictures['BoatNumber'] != "") {
echo " #".$row_rsPictures['BoatNumber'];
} ?><br>driven by: <?php echo $row_rsPictures['DriverName']; ?> at the <?php
$AssocName_array = explode('_', $row_rsPictures['Acronym']);
$AssocName = $AssocName_array[0];
if ($AssocName == "Various") {
$AssocName = "";
}
if ($row_rsPictures['DateTo'] != ""){
$EventYear = date("Y", strtotime($row_rsPictures['DateTo']));
}
else { $EventYear = "";
}
echo $EventYear." ".$AssocName." ".$row_rsPictures['EventName'];?><br>Picture Viewed (<?php echo $row_rsPictures['Views']; ?>) since posted on <?php echo date("n-j-Y", strtotime($row_rsPictures['DatePosted'])); ?>" rel="group">
<img src="../images/gallery/<?php $raceYear = explode('_', $row_rsPictures['EventOverlay']); echo $raceYear[0]; ?>/<?php echo $row_rsPictures['EventOverlay']; ?>/thumb/<?php echo $row_rsPictures['PictureFile']; ?>.jpg" alt="FileName: <?php echo $row_rsPictures['PictureFile'];?>"></a></li>
<?php
} while ($row_rsPictures = mysql_fetch_assoc($rsPictures));
mysql_data_seek($rsPictures, 0);
?>
</ul>
</div>
</div>
and the separate php file that generates the image.
<?php
$filename = explode("_", $_GET['imgID']);
$folder = $filename[0];
$subFolder = $filename[0]."_".$filename[1]."_".$filename[2];
if($filename[3] == "NN") {
$subFolder = $subFolder."_NN";
}
$shot = "../images/gallery/".$folder."/".$subFolder."/".$_GET['imgID'].".jpg";
$watermark = "../images/gallery/watermark.png";
header("Content-type: image/jpg");
$photoImage = ImageCreateFromJPEG($shot);
ImageAlphaBlending($photoImage, true);
$logoImage2 = ImageCreateFromPNG($watermark);
$im = imagecreatetruecolor(800, 16);
$im2 = imagecreatetruecolor(800, 10);
$white = imagecolorallocate($im, 255, 255, 255);
//imagefilledrectangle($photoImage, 0, 0, 796, 15, $white);
$grey = imagecolorallocate($im2, 128, 128, 128);
$red = imagecolorallocate($im2, 255, 0, 0);
//$im = imagecreatetruecolor(796, 25);
$text = $_GET['imgID'];
$text2 = 'COPYRIGHT 1997 - 2011 - DRAGBOATS.COM - ALL RIGHTS RESERVED';
$text3 = '^ THIS BAR WILL NOT APPEAR ON PURCHASED PRINTS ^';
//$black = imagecolorallocate($photoImage, 0, 0, 0);
imagestring($im, 2, 10, 1, $text, $white);
imagestring($im, 2, 440, 1, $text2, $white);
imagestring($im2, 1, 290, 1, $text3, $white);
ImageCopy($photoImage, $im, 0, 0, 0, 0, 800, 16);
ImageCopy($photoImage, $im2, 0, 17, 0, 0, 800, 10);
ImageCopy($photoImage, $logoImage2, 0, 0, 0, 0, 800, 525);
ImageJPEG($photoImage); // output to browser
ImageDestroy($photoImage);
ImageDestroy($logoImage2);
?>
Somewhere there is a conflict that is causing the problem and I can't find it.
Any help is appreciated.
The actual page can be found at http://randykrohn.com/gallery/pictures_test.php?BoatID=881
It appears you're outputting the raw image data (the bytes in the .jpg) file into the gallery popup, with an innappropriate header so that the imgae is being interpreted as text and not an image.
If that last chunk of code under "... the call to GD function" is all in one file, that would explain why. You're outputting a chunk of html, followed by the raw image data, which then gets inserted into the gallery popup. The Content-type header cannot take effect as you've already output some html. If you check your error logs (and/or actually enable errors/warnings), you'd no doubt see the usual "cannot modify headers, output started at line XXX" warnings from PHP.
Try to set php memory limit to 96M (128M - recommended) in php.ini file. If you have no access to that file simply add ini_set('memory_limit', '128M'); to your php file. It must help to solve the issue.
Didn't help, but figured it out on my own. Needed to tell FancyBox to open the link explicitly as an image (ie: fancybox({'type' : 'image'}); Alls well now! Thanks for you help guys!