Is it possible to stretch text using GD in PHP? I need it for captcha, like in this picture(right captcha).
Here is a sample taken from here, there are bunch of options to create a captcha per your needs.
captcha-image.php
<?php
session_start();
//PHP CAPTCHA image
//Generated by https://www.html-code-generator.com/php/captcha-image-code-generator
$width = 130;
$height = 30;
$font_size = 20;
$font = "./verdana.ttf";
$font = realpath($font);
$chars_length = 4;
$captcha_characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$image = imagecreatetruecolor($width, $height);
$bg_color = imagecolorallocate($image, 255, 0, 0);
$font_color = imagecolorallocate($image, 255, 255, 255);
imagefilledrectangle($image, 0, 0, $width, $height, $bg_color);
//background random-line
$vert_line = round($width/5);
$color = imagecolorallocate($image, 255, 255, 255);
for($i=0; $i < $vert_line; $i++) {
imageline($image, rand(0,$width), rand(0,$height), rand(0,$height), rand(0,$width), $color);
}
$xw = ($width/$chars_length);
$x = 0;
$font_gap = $xw/2-$font_size/2;
$digit = '';
for($i = 0; $i < $chars_length; $i++) {
$letter = $captcha_characters[rand(0, strlen($captcha_characters)-1)];
$digit .= $letter;
if ($i == 0) {
$x = 0;
}else {
$x = $xw*$i;
}
imagettftext($image, $font_size, rand(-20,20), $x+$font_gap, rand(22, $height-5), $font_color, $font, $letter);
}
// record token in session variable
$_SESSION['captcha_token'] = strtolower($digit);
// display image
header('Content-Type: image/png');
imagepng($image);
imagedestroy($image);
?>
index.html
<!DOCTYPE html>
<html>
<head>
<title>PHP CAPTCHA Test Form</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta charset="utf-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body>
<div class="p-5">
<div class="card">
<div class="card-header">Message</div>
<div class="card-body">
<form id="contact-form" method="post" action="contact.php">
<div class="form-group row align-items-center">
<label for="message" class="col-sm-2 col-form-label">Message *</label>
<div class="col-sm-10">
<textarea class="form-control" rows="2" name="message" id="message"></textarea>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label">Captcha *</label>
<div class="col-sm-10">
<div class="form-row align-items-center">
<div class="col mb-3">
<input type="text" class="form-control" name="token" id="token" placeholder="Captcha" style="min-width: 150px;">
</div>
<div class="col mb-3">
<img src="./captcha/image.php?12325" alt="CAPTCHA" id="image-captcha">
<i class="material-icons align-middle">refresh</i>
</div>
</div>
</div>
</div>
<button type="submit" class="btn btn-primary" name="submit" id="submit">submit</button>
</form>
</div>
</div>
</div>
<script>
var refreshButton = document.getElementById("refresh-captcha");
var captchaImage = document.getElementById("image-captcha");
refreshButton.onclick = function(event) {
event.preventDefault();
captchaImage.src = './captcha/image.php?' + Date.now();
};
</script>
</body>
</html>
contact.php
<?php
session_start();
if ( isset($_POST['message'], $_POST['token']) ) {
$token = strtolower($_POST['token']);
// validate captcha code
if (isset($_SESSION['captcha_token']) && $_SESSION['captcha_token'] == $token) {
//success your code here
$to = "somebody#example.com";
$subject = "subject";
$message = $_POST['message'];
$headers = "From: webmaster#example.com" . "\r\n" . "CC: somebodyelse#example.com";
//mail($to, $subject, $message, $headers);
echo "success";
} else {
echo "error CAPTCHA code";
}
}
?>
Related
I am struggling with html2pdf - when trying to add the pdf to an email. It is a simple php-form on bootstrap, a modal, and some other nasty code - all works well. Until I come to this part:
The PDF-Creation:
The download version works without issues, yet the pdf which should go with the email remains empty. I have no idea, where I am going the wrong path, so any kind of help would be highly appreciated (as usual)
These are my scripts - the "generatePDF" works perfect, yet the 2nd one not:
<script>
function generatePDF() {
// Choose the element that our container is rendered in.
const element = document.getElementById("form1");
var opt = {
margin: 0.5, //margin for pages
filename: '<?php echo $_POST['Consultant-Nummer']; ?>.pdf',
html2canvas: { scale: 2 },
jsPDF: { unit: 'cm', format: 'A4', orientation: 'portrait' },
pagebreak: { mode: [ 'css', 'legacy'] } //It determines how HTML elements should be split.
};
// Choose the element and save the PDF for our user.
html2pdf(element, opt);
}
</script>
<script>
window.onload = function pdfDivload (){
setTimeout( function pdfDivload (){
let el = document.getElementById('form1');
let opt = {
margin: 1,
filename: '<?php echo $_POST['Consultant-Nummer']; ?>.pdf',
html2canvas: { scale: 2 },
jsPDF: { unit: 'cm', format: 'A4', orientation: 'portrait' },
pagebreak: { mode: [ 'css', 'legacy'] } //It determines how HTML elements should be split.
};
html2pdf().set( opt ).from( el ).toPdf().output('datauristring').then(function( pdfAsString ) {
let data = {
'fileDataURI': pdfAsString,
}
$.post( "preview.php", data);
console.log( data );
} );
}, 3000);
};
</script>
So, where is the issue...?
Edit - here is the full code for this page, is submits the email correctly on load...:
<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;
require("src/PHPMailer.php");
require("src/SMTP.php");
require("src/Exception.php");
if (array_key_exists('Consultant-Nummer', $_POST)) {
$err = false;
$msg = '';
$email = '';
$pdfdoc = $_POST['fileDataURI'];
$b64file = trim( str_replace( 'data:application/pdf;"Konform.pdf";base64,', '', $pdfdoc ) );
$b64file = str_replace( ' ', '+', $b64file );
$decoded_pdf = base64_decode( $b64file );
if (!$err){
$mail = new PHPMailer(true);
$mail->isSMTP();
// $mail->SMTPDebug = 3;
$mail->SMTPSecure = 'tls';
$mail->Host = 'hostname';
// set a port
$mail->Port = 587;
$mail->SMTPAuth = true;
// set login detail for gmail account
$mail->Username = 'username';
$mail->Password = 'password';
$mail->CharSet = 'utf-8';
// set subject
$mail->setFrom('email', 'sendername');
$mail->addAddress('recipient-email');
$mail->addReplyTo('return-email');
// $mail->addAttachment($uploadfile);
$mail->IsHTML(true);
$mail->Subject = "Kontrollformular von: ".$_POST['Consultant-Nummer']."".$_POST['Land']." wegen Auftrag: ".$_POST['Rechnungsnummer']." vom ".$_POST['Rechnungsdatum']."";
$mail->Body = "Some text goes here";
$mail->addStringAttachment($decoded_pdf, "Kontrollformular ".$_POST['Consultant-Nummer'].".pdf",base64);
// $mail->Body = "Hier sind die Daten: ".$_POST['form1']."";
if (!$mail->send()) {
$msg .= "Mailer Error: " . $mail->ErrorInfo;
} else {
header("Refresh:20; url=https://example.com/previouspage.php");
echo '<div class="alert alert-success alert-dismissible">';
echo '×';
echo '<strong>Dankeschön!</strong> Deine Daten sind jetzt zu uns unterwegs!';
echo '</div>';
}
}
}
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<title>MK Online-Form</title>
<link rel="stylesheet" href="css/forms_control.css" type="text/css" />
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.0.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="js/html2pdf.bundle.min.js" type="text/javascript"></script>
<script>
function generatePDF() {
// Choose the element that our container is rendered in.
const element = document.getElementById("form1");
var opt = {
margin: 0.5, //margin for pages
filename: '<?php echo $_POST['Consultant-Nummer']; ?>.pdf',
html2canvas: { scale: 2 },
jsPDF: { unit: 'cm', format: 'A4', orientation: 'portrait' },
pagebreak: { mode: [ 'css', 'legacy'] } //It determines how HTML elements should be split.
};
// Choose the element and save the PDF for our user.
html2pdf(element, opt);
}
</script>
<script>
window.onload = function pdfDivload (){
setTimeout( function pdfDivload (){
let el = document.getElementById('form1');
let opt = {
margin: 1,
filename: '<?php echo $_POST['Consultant-Nummer']; ?>.pdf',
html2canvas: { scale: 2 },
jsPDF: { unit: 'cm', format: 'A4', orientation: 'portrait' },
pagebreak: { mode: [ 'css', 'legacy'] } //It determines how HTML elements should be split.
};
html2pdf().set( opt ).from( el ).toPdf().output('datauristring').then(function( pdfAsString ) {
let data = {
'fileDataURI': pdfAsString,
}
$.post( "preview.php", data);
console.log( data );
} );
}, 3000);
};
</script>
</head>
<form spellcheck="false" enctype="multipart/form-data" method="post" name="form1" id="form1">
<div class="container sub-page form1">
<div class="row">
<div class="col-25">
</div>
<div class="col-50">
<img src="../img/thumbnail_Logo_Final.jpg" width="50%" title="Image">
</div>
<div class="col-25">
</div>
</div>
<h2>KONTROLLFORMULAR</h2>
<div class="row">
<div class="col-lg-6 text-center">
<button type="button" class="btn btn-success pull-left" onclick="generatePDF()" >PDF herunterladen</button>
</div>
</div>
<hr />
<div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
<div class="panel panel-success">
<div class="panel-heading" role="tab" id="generalHeading">
<h4 class="panel-title">
Your entries
</h4>
</div>
<div id="generalInfo" class="panel-collapse collapse in" role="tabpanel">
<div class="panel-body">
<div class="form-horizontal">
<div class="form-group">
<?php
foreach ($_POST as $key => $value) {
echo '<label class="control-label col-md-4">' .$key.'</label>';
echo '<div class="col-md-8"><input type="text" disabled name="'.$key.'" value="'.$value.'"/></div></br>';
}
?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</html>
I am facing a problem in accessing the value of hidden field.
I have made an image cropping application in which i am asking the user to upload an image and a UI is provided to help the user to select the area to crop. Then the top left x and y coordinate and the width and height of the selected area is stored as a semicolon separated string in a hidden input field and when the 'Crop' button is clicked the image and the hidden filed value is passed to the crop.php file. But the values of the hidden field is not accessible in the php file.
My html file which provides browse and crop functionality -
<!doctype html>
<html>
<head>
<title>
Crop
</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript" src="scripts/jquery.imgareaselect.pack.js"></script>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css"
rel = "stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<link rel="stylesheet" type="text/css" href="css/imgareaselect-default.css" />
<script>
var app = angular.module('main-App',[]);
app.controller('AdminController', function($scope, $http) {
$scope.form = [];
$scope.files = [];
$scope.progressBar=0;
$scope.progressCounter=0;
$scope.submit = function() {
alert('Sub');
$scope.form.image = $scope.files[0];
$http({
method : 'POST',
url : 'crop.php',
processData: false,
transformRequest: function (data) {
var formData = new FormData();
formData.append("image", $scope.form.image);
return formData;
},
data : $scope.form,
headers: {
'Content-Type': undefined
},
uploadEventHandlers: {
progress: function (e) {
if (e.lengthComputable) {
$scope.progressBar = (e.loaded / e.total) * 100;
$scope.progressCounter = $scope.progressBar;
$("#completion").css("width", $scope.progressBar+'%');
}
}
}
}).then(function successCallback(response) {
alert($scope.form.params);
});
};
$scope.uploadedFile = function(element) {
$scope.currentFile = element.files[0];
var reader = new FileReader();
reader.onload = function(event) {
$scope.image_source = event.target.result
$scope.$apply(function($scope) {
$scope.files = element.files;
});
}
reader.readAsDataURL(element.files[0]);
$('img#photo').imgAreaSelect({
onSelectStart: {enable:true},
onSelectEnd: function (img, selection) {
document.getElementById("params").value=selection.x1+';'+selection.y1+';'+selection.width+';'+selection.height;
alert(document.getElementById("params").value);
}
});
}
});
</script>
<style>
html,body {
height: 100%;
}
.wrapper{
height:auto;
}
.wrapper img {
height:100%;
color:grey;
text-align: center;
line-height:100px;
vertical-align: middle;
padding:0px;
margin:0px;
}
</style>
</head>
<body>
<div ng-app="main-App" ng-controller="AdminController">
<form ng-submit="submit()" name="form" role="form" enctype="multipart/form-data">
<div class="container-fluid">
<div class="row flex-items-xs-center">
<div class="col-md-9">
<div class="container-fluid">
<div class="row">
<div class="col-md-9">
<div class="wrapper">
<img id="photo" name="photo" src="{{image_source}}" alt="Image preview..." class="img-responsive img-thumbnail" style="border-style:dashed">
</div>
</div>
</div>
</div>
<br/>
<br/>
<div class="container-fluid">
<div class="row">
<div class="col-md-2">
<label class="btn btn-primary">
<input ng-model="form.image" type="file" class="form-control input-lg" name="image" id="image"
accept = "image/*"
onchange="angular.element(this).scope().uploadedFile(this)"
style="display:none;" >
<span class="glyphicon glyphicon-folder-open"></span>
Browse
</label>
</div>
<div class="col-md-2">
<label class="btn btn-success">
<input type="submit" id="submit" value="Submit" style="display:none;"/>
<span class="glyphicon glyphicon-cloud-upload"></span>
Crop
</label>
</div>
</div>
</div>
</div>
</div>
</div>
<input type="hidden" name="params" id="params" value="0;0;0;0" ng-model="params" />
</form>
<br/>
<br/>
<div class="container-fluid">
<div class="row">
<div class="col-md-9">
<div class="progress-bar progress-bar-success progress-bar-striped" role="progressbar" id ="completion" name="completion"
aria-valuenow="0" aria-valuemin="0" aria-valuemax="50" style="width:0%;height:10px;border-width:0px;border-radius:2px;">
</div>
</div>
</div>
</div>
</div>
<br/>
<br/>
the UI -
crop.php -
<?php
$uncropped_path = '/var/www/html/images/original/';
$cropped_path = '/var/www/html/images/cropped/';
if(isset($_FILES['image'])){
//$ext = pathinfo($_FILES['image']['name'],PATHINFO_EXTENSION);
$image = $_FILES['image']['name'];
move_uploaded_file($_FILES["image"]["tmp_name"], $uncropped_path.$image);
$data = json_decode(file_get_contents("php://input"));
print_r($data);
}else{
echo "Image Is Empty";
}
function doResize($filename,$size,$resize_path)
{
$image = new Imagick();
$file = file_get_contents($filename);
$image->readImageBlob($file);
$dimensions = $image->getImageGeometry();
$pathInfo = pathinfo($filename);
$name = $pathInfo['filename'];
$srcWidth = $dimensions['width'];
$srcHeight = $dimensions['height'];
list($resWidth,$resHeight) = getResizeDim($size,$srcWidth,$srcHeight);
$image->resizeImage($resWidth,$resHeight,Imagick::FILTER_LANCZOS,.85);
$image->writeImage($resize_path);
}
function getResizeDim($size,$srcWidth,$srcHeight)
{
$width;
$height;
if($srcHeight > $srcWidth)
{
if($srcHeight > $size)
$height = $size;
else $height = $srcHeight;
$width = ceil($height*($srcWidth/$srcHeight));
}
else {
if($srcWidth > $size)
$width = $size;
else $width = $srcWidth;
$height = ceil($width*($srcHeight/$srcWidth));
}
return array($width,$height);
}
When i try to print the data received in php i get the following -
Moreover the data array in the php seems to be empty.
I have read various similar questions on stackoverflow but none of them worked in my case.
When I upload file on my localhost it works fine. But when I upload it on the server it doesn't work. Image is displaying on that page correctly from same directory but it has problem in uploading file to that directory.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Belvic Print - Home page</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=3.0, user-scalable=yes"/>
<meta name="description" content="Printing template">
<meta name="author" content="Netbase">
<!--Add css lib-->
<link href='http://fonts.googleapis.com/css?family=Roboto:500,300,700,400' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Arimo:500,300,700,400' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Roboto+Condensed:500,300,700,400' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="bootstrap-3.3.6-dist/css/bootstrap.min.css">
<link rel="stylesheet" href="bootstrap-3.3.6-dist/font-awesome-4.5.0/css/font-awesome.css">
<link rel="stylesheet" href="sidebar.css">
<script src="bootstrap-3.3.6-dist/js/jquery-1.12.2.min.js"></script>
<script src="bootstrap-3.3.6-dist/js/bootstrap.min.js"></script>
<script src="code_adimn.js"></script>
<script src="script.js"></script>
<style>
body{
position: relative;
overflow-x: hidden;
}
.main-container{
margin:0;
padding:0;
}
.submit_button{
border: none;
margin-top: 5%;
padding: 10px;
}
label.myLabel input[type="file"] {
position: fixed;
top: -1000px;
}
.col-lg-offset-4{
margin-bottom: 5%;
}
.row{
margin-top: 3%;
}
/***** Example custom styling *****/
.myLabel {
/*border: 2px solid #AAA;*/
padding: 10px;
margin-top: 5%;
background: #DDD;
display: inline-block;
}
.myLabel:hover {
background: #CCC;
}
.myLabel:active {
background: #CCF;
}
.myLabel :invalid + span {
color: #A44;
}
.myLabel :valid + span {
color: #4A4;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<div class="navibar">
<div class="fa fa-bars"> <span> Menu Bar </span></div>
<ul>
<div class="fa fa-close"></div>
<h2 class="admin">Admin Panel</h2>
<li>Image 1</li>
<li>Image 2</li>
<li>Image 3</li>
</ul>
</div>
<div class="row img-row">
<div id="first" class="rows col-lg-6 col-sm-10 col-sm-offset-1 col-xs-10 col-xs-offset-1 col-lg-offset-4">
<?php
include("db.php");
$res = mysqli_query($conn, "SELECT * FROM image WHERE id=1");
while ($record = mysqli_fetch_array($res)) {
?>
<img src="<?php echo "../images/slider/home/" . $record['image1']; ?>" alt="" width="100%">//This image is displaying correctly from same directory
<form enctype="multipart/form-data" action="slider.php" method="POST" >
<label class="myLabel">
<input type="file" name="myfile1"/>
<span>Change Picture</span>
</label>
<input name="submit1" type="submit" class="submit_button">
<div class="clearfix"></div>
</form>
<form action="slider.php" method="POST" enctype="multipart/form-data">
<label name="description">Enter the heading: </label>
<input type="text" name="heading1" class="form-control" placeholder="Enter the heading" value="<?php echo $record['image2']; ?>">
<br>
<label name="description">Enter the Description</label>
<textarea name="description1" class="form-control" rows="3"><?php echo $record['image3'];} ?></textarea>
<input name="submit_content1" type="submit" class="pull-left submit_button">
</form>
</div>
<div id="second" class="rows col-lg-6 col-sm-10 col-sm-offset-1 col-xs-10 col-xs-offset-1 col-lg-offset-4">
<?php
$res1 = mysqli_query($conn, "SELECT * FROM image WHERE id=1");
while ($record1 = mysqli_fetch_array($res1)) {
?>
<img src="<?php echo "../images/slider/home/" . $record1['image4']; ?>" alt="kk" width="100%">
<form action="slider.php" method="POST" enctype="multipart/form-data">
<label class="myLabel">
<input type="file" name="myfile2"/>
<span>Upload Picture</span>
</label>
<input name="submit2" type="submit" class="submit_button">
<div class="clearfix"></div>
</form>
<form action="slider.php" method="POST" enctype="multipart/form-data">
<label name="description">Enter the heading: </label>
<input type="text" name="heading2" class="form-control" placeholder="Enter the heading" value="<?php echo $record1['image5']; ?>">
<br>
<label name="description">Enter the Description</label>
<textarea name="description2" class="form-control" rows="3"><?php echo $record1['image6'];} ?></textarea>
<input name="submit_content2" type="submit" class="pull-left submit_button">
</form>
</div>
<div id="third" class="rows col-lg-6 col-sm-10 col-sm-offset-1 col-xs-10 col-xs-offset-1 col-lg-offset-4">
<?php
$res2 = mysqli_query($conn, "SELECT * FROM image WHERE id=1");
while ($record2 = mysqli_fetch_array($res2)) {
?>
<img src="<?php echo "../images/slider/home/" . $record2['image7']; ?>" alt="" width="100%">
<form action="slider.php" method="POST" enctype="multipart/form-data">
<label class="myLabel">
<input type="file" name="myfile3"/>
<span>Upload Picture</span>
</label>
<input name="submit3" type="submit" class="submit_button">
<div class="clearfix"></div>
</form>
<form action="slider.php" method="POST" enctype="multipart/form-data">
<label name="description">Enter the heading: </label>
<input type="text" name="heading3" class="form-control" placeholder="Enter the heading" value="<?php echo $record2['image8']; ?>">
<br>
<label name="description">Enter the Description</label>
<textarea name="description3" class="form-control" rows="3"><?php echo $record2['image9'];} ?></textarea>
<input name="submit_content3" type="submit" class="pull-left submit_button">
</form>
</div>
</div>
</div>
<?php
if (isset($_POST['submit1'])) {
$type = $_FILES["myfile1"]["type"];
$size = $_FILES["myfile1"]["size"];
$temp = $_FILES["myfile1"]["tmp_name"];
$error = $_FILES["myfile1"]["error"];
if ($_FILES["myfile1"]["error"] < 1) {
if (exif_imagetype($_FILES["myfile1"]["tmp_name"]) != IMAGETYPE_PNG && exif_imagetype($_FILES["myfile1"]["tmp_name"]) != IMAGETYPE_JPEG
&& exif_imagetype($_FILES["myfile1"]["tmp_name"]) != IMAGETYPE_GIF && exif_imagetype($_FILES["myfile1"]["tmp_name"]) != IMAGETYPE_ICO) {
echo 'There is problem with image file or file is not image';
} else {
$name = "image_" . date('Y-m-d-H-i-s') . '_' . uniqid() . '.jpg';
$upload = move_uploaded_file($temp, "../images/slider/home/" . $name);
if ($_FILES["myfile1"]["error"] > 0) {
echo "Some error in file upload";
} else {
$sql = "UPDATE image SET image1='$name' WHERE id=1";
if (mysqli_query($conn, $sql) && $upload) {
echo "Refresh the page to see the effect";
} else {
echo "Some error while updating image";
}
}
}
}
else {
echo "There is error in image file";
}
}
//For image 2
if (isset($_POST['submit2'])) {
$type = $_FILES["myfile2"]["type"];
$size = $_FILES["myfile2"]["size"];
$temp = $_FILES["myfile2"]["tmp_name"];
$error = $_FILES["myfile2"]["error"];
if ($_FILES["myfile2"]["error"] < 1) {
if (exif_imagetype($_FILES["myfile2"]["tmp_name"]) != IMAGETYPE_PNG && exif_imagetype($_FILES["myfile2"]["tmp_name"]) != IMAGETYPE_JPEG
&& exif_imagetype($_FILES["myfile2"]["tmp_name"]) != IMAGETYPE_GIF && exif_imagetype($_FILES["myfile2"]["tmp_name"]) != IMAGETYPE_ICO) {
echo 'There is problem with image file or file is not image';
} else {
$name = "image_" . date('Y-m-d-H-i-s') . '_' . uniqid() . '.jpg';
$upload = move_uploaded_file($temp, "../images/slider/home/" . $name);
if ($_FILES["myfile2"]["error"] > 0) {
echo "Some error in file upload";
} else {
$sql = "UPDATE image SET image4='$name' WHERE id=1";
if (mysqli_query($conn, $sql) && $upload) {
echo "Refresh the page to see the effect";
} else {
echo "Some error while updating image";
}
}
}
}
else {
echo "There is error in image file";
}
}
//For image 3
if (isset($_POST['submit3'])) {
$type = $_FILES["myfile3"]["type"];
$size = $_FILES["myfile3"]["size"];
$temp = $_FILES["myfile3"]["tmp_name"];
$error = $_FILES["myfile3"]["error"];
if ($_FILES["myfile3"]["error"] < 1) {
if (exif_imagetype($_FILES["myfile3"]["tmp_name"]) != IMAGETYPE_PNG && exif_imagetype($_FILES["myfile3"]["tmp_name"]) != IMAGETYPE_JPEG
&& exif_imagetype($_FILES["myfile3"]["tmp_name"]) != IMAGETYPE_GIF && exif_imagetype($_FILES["myfile3"]["tmp_name"]) != IMAGETYPE_ICO) {
echo 'There is problem with image file or file is not image';
} else {
$name = "image_" . date('Y-m-d-H-i-s') . '_' . uniqid() . '.jpg';
$upload = move_uploaded_file($temp, "../images/slider/home/" . $name);
if ($_FILES["myfile3"]["error"] > 0) {
echo "Some error in file upload";
} else {
$sql = "UPDATE image SET image7='$name' WHERE id=1";
if (mysqli_query($conn, $sql) && $upload) {
echo "Refresh the page to see the effect";
} else {
echo "Some error while updating image";
}
}
}
}
else {
echo "There is error in image file";
}
}
//For content 1
if (isset($_POST['submit_content1'])) {
$heading1 = $_POST['heading1'];
$description1 = $_POST['description1'];
$update1 = "UPDATE image SET image2='$heading1', image3='$description1' WHERE id=1";
if (mysqli_query($conn, $update1)) {
echo "";
} else {
echo mysqli_error($conn);
}
}
//For content 2
if (isset($_POST['submit_content2'])) {
$heading2 = $_POST['heading2'];
$description2 = $_POST['description2'];
$update2 = "UPDATE image SET image5='$heading2', image6='$description2' WHERE id=1";
if (mysqli_query($conn, $update2)) {
echo "";
} else {
echo mysqli_error($conn);
}
}
//For content 3
if (isset($_POST['submit_content3'])) {
$heading3 = $_POST['heading3'];
$description3 = $_POST['description3'];
$update3 = "UPDATE image SET image8='$heading3', image6='$description3' WHERE id=1";
if (mysqli_query($conn, $update3)) {
echo "";
} else {
echo mysqli_error($conn);
}
}
?>
</body>
add this 2 lines on php.ini (or unquote it)
extension=php_mbstring.dll
extension=php_exif.dll
and like i said use is_uploaded_file before moving files :)
Working stencil art.Here i have converted text to image this is working good i have 3 text box every text box generating separate line of image on browser.The problem is that i have three another text box for to change the font size of that each converted text.I am not getting any idea how to 3 different font size variable to converted text to change font size because.
Demo Link:- Click Here
Bellow is snap shot what i exactly want.Here you can see that every line of text font size you can change through font size text (Line Height).
My index.php sample code
<?php
?>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
/*
$( "#target" ).change(function() {
// alert( "Handler for .change() called." );
var fontname = this.value;
//alert(fontname);
var img_text = $('input[name="stencil-text"]').map(function(){
return $(this).val();
}).get();
var img = $("<img />").attr('src', 'some.php?img=' + img_text+'&fontname='+fontname).load(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#stencil-main").html(img);
}
});
});
*/
$('input[name="stencil-text"]').keyup(function(){
var img_text = $('input[name="stencil-text"]').map(function(){
return $(this).val();
}).get();
var fontsize = $('input[name="stencil-text-size"]').map(function(){
return $(this).val();
}).get();
// var img = $("<img />").attr('src', 'some.php?img=' + img_text).load(function() {
var img = $("<img />").attr('src', 'some.php?img=' + img_text+'&fontsize='+fontsize).load(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#stencil-main").html(img);
}
});
});
});
</script>
</head>
<body>
<div id ="all">
<div id="box" style="margin-left: 394px;">
<span class="line" style="margin-left: 578px;">FONT SIZE LINE1 -</span>
<input type="text" name="stencil-text-size" value="20" style="margin-left: 15px;">
<span class="line" style="margin-left: 578px;">LINE 1-</span>
<input type="text" name="stencil-text" style="margin-left: 15px;">
<br>
<span class="line" style="margin-left: 578px;">FONT SIZE LINE 2 -</span>
<input type="text" name="stencil-text-size2" style="margin-left: 15px;">
<span class="line" style="margin-left: 578px;">LINE 2-</span>
<input type="text" name="stencil-text" style="margin-left: 15px;">
<br>
<span class="line" style="margin-left: 578px;">FONT SIZE LINE 3 -</span>
<input type="text" name="stencil-text-size3" style="margin-left: 15px;">
<span class="line" style="margin-left: 578px;">LINE 3-</span>
<input type="text" name="stencil-text" style="margin-left: 15px;">
</div>
<div id="stencil-main" style="margin-top: -652px;"></div>
</div>
<!-- <select id="target">
<option value="ByzantineEmpire" selected="selected">Byzan</option>
<option value="arial">Arial</option>
</select> -->
</body>
</html>
My some.php sample code to convert text to image
<?php
header("Content-type: image/png");
$cid = str_replace(',', "\n", $_GET['img']);
//$cid = array('s1=> ','s2=> ' ,'s3=> ').str_replace(',', "\n", $_GET['img']);
//$fsize="20";
$fontname=$_GET['fontname'] ;
$fontsize=$_GET['fontsize'] ;
####################### BEGIN USER EDITS #######################
//$imagewidth = 500;
//$imageheight = 250;
$imagewidth = 800;
$imageheight = 1000;
//$fontsize = "20";
$fontsize = $fontsize;
$fontangle = "0";
$font = "ByzantineEmpire.ttf";
//$font = $fontname.'.ttf';
$text = $cid ;
$text2="sanjay";
$backgroundcolor = "FFFFFF";
$textcolor = "#000000";
######################## END USER EDITS ########################
### Convert HTML backgound color to RGB
if( #eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $backgroundcolor, $bgrgb ) )
{$bgred = hexdec( $bgrgb[1] ); $bggreen = hexdec( $bgrgb[2] ); $bgblue = hexdec( $bgrgb[3] );}
### Convert HTML text color to RGB
if( #eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $textcolor, $textrgb ) )
{$textred = hexdec( $textrgb[1] ); $textgreen = hexdec( $textrgb[2] ); $textblue = hexdec( $textrgb[3] );}
### Create image
$im = imagecreate( $imagewidth, $imageheight );
### Declare image's background color
$bgcolor = imagecolorallocate($im, $bgred,$bggreen,$bgblue);
### Declare image's text color
$fontcolor = imagecolorallocate($im, $textred,$textgreen,$textblue);
### Get exact dimensions of text string
$box = imageTTFBbox($fontsize,$fontangle,$font,$text);
### Get width of text from dimensions
$textwidth = abs($box[4] - $box[0]);
### Get height of text from dimensions
$textheight = abs($box[5] - $box[1]);
### Get x-coordinate of centered text horizontally using length of the image and length of the text
$xcord = ($imagewidth/2)-($textwidth/2)-2;
### Get y-coordinate of centered text vertically using height of the image and height of the text
$ycord = ($imageheight/2)+($textheight/2);
### Declare completed image with colors, font, text, and text location
imagettftext ( $im, $fontsize, $fontangle, $xcord, $ycord, $fontcolor, $font, $text );
### Display completed image as PNG
$html=imagepng($im);
### Close the image
imagedestroy($im);
?>
I did this really quickly to show you how to change the font-size of each of the boxes using jQuery - http://jsfiddle.net/jayblanchard/FB5fL/
$('#set').click(function(e) {
e.preventDefault();
$('.stencil-text').each(function(index) { // loop through each text box
var fontSize = $(this).prevAll('.stencil-text-size').val(); // get the font-size for the current text box
var fontText = $(this).val(); // get the text
console.log(fontSize +' '+ fontText); // just for testing
var newSpan = '<span>' + fontText + '</span><br />'; // set up a new span with the text
$('#stencil-main').append(newSpan); // append the new span
$('#stencil-main span:last').css({ // modify the new span's CSS
"font-size": fontSize + 'px',
"color": "red"
});
});
});
I added classes to the inputs so that they could be re-used instead of doing a function for each individual input by name. Perhaps you can modify this to use with your code.
After some struggle i have made this answer get the text and font size variable and explode it as an array like bellow.
Demo Link:- Click Here
$myArray = explode(',', $_GET['img']);
$fontarray = explode(',' , $_GET['fontsize']);
Use the for loop to looping array
for($i=0;$i<$count;$i++)
{
$newcount=count($fontarray);
for($j=0;$j<$newcount;$j++)
{
if($j==$i)
{
$xcord=$xcord+2;
$ycord=$ycord+100;
imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $myArray[$i] );
}
}
}
And pass that explode array in image text function like bellow.
imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $myArray[$i] );
Full solution to convert text image and change the font of text line by line
1) Create index.php with bellow code
<?php
?>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('input[name="stencil-text"]').keyup(function(){
var img_text = $('input[name="stencil-text"]').map(function(){
return $(this).val();
}).get();
var fontsize = $('input[name="stencil-text-size"]').map(function(){
return $(this).val();
}).get();
var img = $("<img />").attr('src', 'some.php?img=' + img_text+'&fontsize='+fontsize).load(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
//alert(fontsize);
$("#stencil-main").html(img);
}
});
});
$('input[name="stencil-text-size"]').keyup(function(){
var img_text = $('input[name="stencil-text"]').map(function(){
return $(this).val();
}).get();
var fontsize = $('input[name="stencil-text-size"]').map(function(){
return $(this).val();
}).get();
var img = $("<img />").attr('src', 'some.php?img=' + img_text+'&fontsize='+fontsize).load(function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
//alert(fontsize);
$("#stencil-main").html(img);
}
});
});
});
</script>
</head>
<body>
<div id ="all">
<div id="box" style="margin-left: 360px;">
<span class="line" style="margin-left: 578px;">FONT SIZE LINE1 -</span>
<input type="text" name="stencil-text-size" value="100" style="margin-left: 15px;">
<span class="line" style="margin-left: 578px;">LINE 1-</span>
<input type="text" name="stencil-text" style="margin-left: 15px;">
<br>
<span class="line" style="margin-left: 578px;">FONT SIZE LINE2 -</span>
<input type="text" name="stencil-text-size" value="50" style="margin-left: 15px;">
<span class="line" style="margin-left: 578px;">LINE 2-</span>
<input type="text" name="stencil-text" style="margin-left: 15px;">
<br>
<span class="line" style="margin-left: 578px;">FONT SIZE LINE3 -</span>
<input type="text" name="stencil-text-size" value="20" style="margin-left: 15px;">
<span class="line" style="margin-left: 578px;">LINE 3-</span>
<input type="text" name="stencil-text" style="margin-left: 15px;">
</div>
<div id="stencil-main" style="margin-top: -652px;margin-left:-297px"></div>
</div>
</body>
</html>
2) Create some.php with bellow code
<?php
header("Content-type: image/png");
$myArray = explode(',', $_GET['img']);
$fontarray = explode(',' , $_GET['fontsize']);
####################### BEGIN USER EDITS #######################
$imagewidth = 1000;
$imageheight = 1000;
$fontangle = "0";
$font = "ByzantineEmpire.ttf";
$backgroundcolor = "FFFFFF";
$textcolor = "#000000";
######################## END USER EDITS ########################
### Convert HTML backgound color to RGB
if( #eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $backgroundcolor, $bgrgb ) )
{$bgred = hexdec( $bgrgb[1] ); $bggreen = hexdec( $bgrgb[2] ); $bgblue = hexdec( $bgrgb[3] );}
### Convert HTML text color to RGB
if( #eregi( "([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})", $textcolor, $textrgb ) )
{$textred = hexdec( $textrgb[1] ); $textgreen = hexdec( $textrgb[2] ); $textblue = hexdec( $textrgb[3] );}
### Create image
$im = imagecreate( $imagewidth, $imageheight );
### Declare image's background color
$bgcolor = imagecolorallocate($im, $bgred,$bggreen,$bgblue);
### Declare image's text color
$fontcolor = imagecolorallocate($im, $textred,$textgreen,$textblue);
### Get exact dimensions of text string
### Declare completed image with colors, font, text, and text location
$count=count($myArray);
$box = imageTTFBbox(50,$fontangle,$font,'test');
### Get width of text from dimensions
$textwidth = abs($box[4] - $box[0]);
### Get height of text from dimensions
$textheight = abs($box[5] - $box[1]);
### Get x-coordinate of centered text horizontally using length of the image and length of the text
$xcord = ($imagewidth/2)-($textwidth/2)-2;
### Get y-coordinate of centered text vertically using height of the image and height of the text
$ycord = ($imageheight/2)+($textheight/2);
for($i=0;$i<$count;$i++)
{
$newcount=count($fontarray);
for($j=0;$j<$newcount;$j++)
{
if($j==$i)
{
$xcord=$xcord+2;
$ycord=$ycord+100;
imagettftext ( $im, $fontarray[$j], $fontangle, $xcord, $ycord, $fontcolor, $font, $myArray[$i] );
}
}
}
$html=imagepng($im);
### Close the image
imagedestroy($im);
?>
You will get like bellow snap shot sample out put after run the code
I have a map for an RPG that I'm building. The map is overlaid with a grid of cells, each cell 50px x 50px. each cell should be clickable, but with so many clickable cells on an 800px by 800px map, my script uses up the allocated memory no matter how high i set it (last attempt was 250M). as you can see in the code below, I'm using the base64 encoding and then putting the image into the tag. I believe this may be part of the issue, but i don't want users being able to see the information in the map. how can i accomplish this and stay under the memory limit?
<?php
define("IN_GAME", true);
ini_set("memory_limit","500M");
function imagegrid($image, $w, $h, $s, $color)
{
for($iw = 1; $iw < $w/$s; $iw++)
{
imageline($image, $iw*$s, 0, $iw*$s, $w, $color);
}
for($ih = 1; $ih < $h/$s; $ih++)
{
imageline($image, 0, $ih*$s, $w, $ih*$s, $color);
}
}
$width = 800;
$height = 800;
$block_size = 50;
$image = "images/maps/world.png";
$img = imagecreatefrompng($image);
$grid = imagecolorallocate($img, 0, 0, 0);
imagesetstyle($img, $grid);
imagegrid($img, $width, $height, $block_size, IMG_COLOR_STYLED);
ob_start();
imagepng($img);
$contents = ob_get_contents();
ob_end_clean();
$img_STR = "data:image/png;base64,".base64_encode($contents);
imagedestroy($img);
$split = $width/$block_size;
$c = 1;
while($c < $split)
{
if($c = 1)
{
$x1 = $c;
}
else
{
$x1 = $c*$block_size;
}
if($c = 1)
{
$y1 = $c;
}
else
{
$y1 = $c*$block_size;
}
$x2 = $x1*$block_size;
$y2 = $y1*$block_size;
if(sizeof($coords))
{
array_push($coords, $x1);
array_push($coords, $y1);
array_push($coords, $x2);
array_push($coords, $y2);
}
else
{
echo $x1.','.$x2.','.$y1.','.$y2;
$coords = array($x1, $y1, $x2, $y2);
}
}
if (isset($ts_x) || ($_SERVER['QUERY_STRING'] != ""))
{
if (isset($ts_x))
{
$clickedX = $ts_x;
$clickedY = $ts_y;
}
else
{
list($clickedX, $clickedY) = split(",", $_SERVER['QUERY_STRING'], 2);
}
require 'inc.php';
$allowed = false;
$allowed = inCoord('circ',$coords, $clickedX, $clickedY);
if($allowed)
{
?>
<html>
<head>
<title>PHP Image Map</title>
</head>
<body bgcolor="#00FFC8">
<p align="center">
<b> Aye Eye you got in!</b>
<br>
Click Here to Go to main
</p>
</body>
</html>
<?php
}
else
{
//include 'miss_it.inc';
?>
<html>
<head>
<title>PHP Image Map</title>
</head>
<body bgcolor="#8BCBF8">
<form METHOD="POST" action="">
<p align="center">
<span style="cursor:default;">
<input type="image" src="<?php echo $img_STR; ?>" name="ts">
</span>
</p>
</form>
</body>
</html>
<?php
}
}
else
{
?>
<html>
<head>
<title>PHP Image Map</title>
</head>
<body bgcolor="#8BCBF8">
<form METHOD="POST" action="">
<p align="center">
<span style="cursor:default;">
<input type="image" src="<?php echo $img_STR; ?>" name="ts">
</span>
</p>
</form>
</body>
</html>
<?php
}
?>