Can't Create Session Inside image.php in Codeigniter - php

I want to create a simple captcha verification form and it looks like this:
<form>
<br/>Captcha :<img class="captcha" src="<?php echo base_url('application/views/captcha/image.php')?>">
<br/><br/><input type="username" required class="i" name="captcha" id="i7" size="25"/>
<br><br><input type="submit" name="Submit" id="submit" value="Register"/>
</form>
Here's the image.php file:
<?php
session_start();
header("Content-Type: image/png");
$text = rand(1000,100000);
$_SESSION['code'] = $text;
$img = imagecreatefromjpeg("bg.jpg");
$font = "arial.ttf";
$R = rand(0,100);
$G = rand(0,100);
$B = rand(0,100);
$TxtColor = imagecolorallocate($img,$R,$G,$B);
imagettftext($img,rand(40,45),rand(0,1),rand(10,70),rand(38,50),$TxtColor,$font$text);
imagepng($img);
imagedestroy($img);
?>
It works fine outside Codeigniter. In Codeigniter, whenever I try to retrieve the value of $text from the session I get an error message as "Undefined index: code". If I use Codeigniter's userdata() method as following:
$this->session->set_userdata($text);
The captcha image doesn't even show.

In Codignitor you need to load session library before set the session:
$this->load->library('session');
Than you can set session by using array:
$array["code"] = $text;
$this->session->set_userdata($array);
When you need to print:
$this->session->userdata("code");
CI SESSION USER GUIDE

Related

Save input data in php file (No DB)

Is it possible to save input data in php file without using any database?
Something like:
echo " inputted text.. ";
or
$text = "Text..";
Use fwrite, very easy :
<?php
$fp = fopen('myfile.txt', 'w');
fwrite($fp, 'this is my database without database :p ');
fclose($fp);
?>
If you want to work with a form, and extract some variables into a file you can use:
Your Form in form.html
<form action="recipient.php" method="POST">
INPUT1: <input type="text" name="text1" id="input1"><br/>
INPUT2: <input type="text" name="text2" id="input2"><br/>
FILENAME: <input type="text" name="filename" id="filename">
<button type="submit">Send now</button>
</form>
Your PHP recipient.php - without any validation checks:
<?php
$varA = "\$varA = ".$_POST['input1'].";"; // put your string into varible $varA
$varB = "\$varB = ".$_POST['input1'].";"; // put your string into varible $varA
$fileName = $_POST['filename']; // set a filename from form field
$text = $varA ." ". $varB; // add all together
$filepath = fopen('/var/www/html/'.$fileName.'.php', 'w+'); // set filepath and fopen to new PHP-file
fwrite($filepath, '<?php '. $text); // write text as PHP-file
fclose($filepath); // close file
?>
If you haven't read about them yet check HTML-Forms.
You might also want to look into arrays and serialisation.
But apart from that I highly recommend to have a look into Databases (PDO) - it safes you time and is much more secure.

how to validate CAPTCHA using php and jquery

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>

Post Back variable value for captcha

i want the value of $code variable to get on my other page--- captcha.php.
captcha_image.php
$captcha = new CaptchaCode(); //class defined in captcha_code.php
$code = str_encrypt($captcha->generateCode(6)); //function defined in captcha_code.php
$captcha1 = new CaptchaImages();
$captcha1-> GenerateImage($width,$height,str_decrypt($code));
captcha.php
<img style="cursor: pointer;width: 50px;height: 50px;" src="refresh.png" onclick="refresh_captcha();"/>
<input type="hidden" name="security_check" value="<?php echo $code; ?>"> // want value of $code here
<script type="text/javascript">
function refresh_captcha()
{
var img = document.getElementById('captcha_img');
img.src = 'captcha_images.php';
jQuery("#captcha_img").attr("src",img.src);
}
</script>
I cant include captcha_images.php file in my code and even dont want it to be done using sessions, tried that way.If anyone has a solution for this, please help me to solve this issue.
Better solution is save code into SESSION.
For example:
captcha_image.php:
session_start();
$captcha = new CaptchaCode();
$code = $captcha->generateCode(6);
$captcha1 = new CaptchaImages();
$captcha1-> GenerateImage($width,$height,$code);
$_SESSION["captchacode"] = $code;
And check correctness after submit of the form:
session_start();
...
if($_SESSION["captchacode"]!=$_POST["security_check"]){
echo "Wrong captcha!";
}else{
// captcha is correct, process the form
}
If you cannot use cookies and session, you cannot get information from captcha_image.php which returns only image. You must generate information in else request, for example:
<img id="captcha_img" src="captcha_images.php?encoded_code=<?php echo $code ?>" onclick="refresh_captcha();"/>
<input type="hidden" id="captcha_hidden" name="security_check" value="<?php echo $code ?>">
<script type="text/javascript">
function refresh_captcha()
{
// generate_captcha.php returns only encoded captcha
$.get('generate_captcha.php', function(encoded_code) {
$('#captcha_hidden').val(encoded_code);
$('#captcha_img').attr("src","captcha_images.php?encoded_code="+encoded_code);
});
}
</script>
Here generate_captcha.php returns encoded captcha, captcha_images.php doesnt generate code, only decode code from hims parameter encoded_code and this code is also inserted into hidden.

Need Help To Solve Images Disppeared After Again Form Submiitted?

i have multiple image upload options in the form and they are working fine and update file name in the mysql database columns?
when i uploads image1 then image move on to the server and also it is showing next to html table columns now problem is that when i upload image with file option2 after form submit then image1 which is on the next to the image1 file option will be disappeared and in the mysql database image1 columns will be blank?
Multiple Images Uploading Functions
$id=$_REQUEST['id'];
if(isset($_POST['submit']))
{
if (!empty($_FILES['image']['name']))
{
$rnd_1 = rand(11111,99999);
$file_name= $rnd_1.'_'.$_FILES['image']["name"];
$file_path = "uploads/";
$image = new imgMark();
$image->font_path = "arial.ttf";
$image->font_size = 25;
$image->water_mark_text = "© www.edge.pk";
$image->color = 'CC003E';
$image->opacity = 50;
$image->rotation = 0;
if($image->convertImage('image', $file_name, $file_path))
$demo_image = $image->img_path;
}
if (!empty($_FILES['image1']['name']))
{
$rnd_1 = rand(11111,99999);
$file_name= $rnd_1.'_'.$_FILES['image1']["name"];
$file_path = "uploads/";
$image = new imgMark();
$image->font_path = "arial.ttf";
$image->font_size = 35;
$image->water_mark_text = "© www.edge.pk";
$image->color = 'CC003E';
$image->opacity = 50;
$image->rotation = 0;
if($image->convertImage('image1', $file_name, $file_path))
$demo_image2 = $image->img_path;
}
if (!empty($_FILES['image2']['name']))
{
$rnd_1 = rand(11111,99999);
$file_name= $rnd_1.'_'.$_FILES['image2']["name"];
$file_path = "uploads/";
$image = new imgMark();
$image->font_path = "arial.ttf";
$image->font_size = 35;
$image->water_mark_text = "© www.edge.pk";
$image->color = 'CC003E';
$image->opacity = 50;
$image->rotation = 0;
if($image->convertImage('image2', $file_name, $file_path))
$demo_image3 = $image->img_path;
}
Update Query
UPDATE products SET
image='$demo_image',addimage1='$demo_image2',addimage2='$demo_image3'
WHERE id='$id'
}
Select Images Query
$query1=mysql_query("select images,addimages1,addimages2 from products
where id='$id' ")or die("query");
$row2=mysql_fetch_array($query1);
<form method="post" enctype="multipart/form-data">
Image Upload Option1
<input type="file" name="image" id="image" />
<img src="<?php echo $image['image'] ?>" width="150" height="150" />
Image Upload Option2
<input type="file" name="image1" id="image1"/>
<img src="<?php echo $image['addimage1'] ?>" width="150" height="150" />
Image Upload Option3
<input type="file" name="image2" id="image2"/>
<img src="<?php echo $image['addimage2'] ?>" width="150" height="150" />
<input type="submit" class="bg" name="submit" />
</form>
The problem lays here:
UPDATE products SET
image='$demo_image',addimage1='$demo_image2',addimage2='$demo_image3'
WHERE id='$id'
}
From what I understood you first submit the form where you upload the first image and then you submit the form again where you upload the second image. The reason of this is that during your second upload the variable $demo_image will be blank because you are not sending any value of the input "image" during the resubmit. See here:
$demo_image = $image->img_path;
$image->img_path is blank, therefore $demo_image will be blank (or NULL? - not sure) as well.
There are many solutions of this problem. You can retrieve data from you db to the form and then resubmit, or test if your variables are blank (or NULL?) and then having different UPDATE commands for different variations, or retrieving data from MySQL just before you run UPDATE and many more.
I'd pick retrieving "old" data from MySQL and then just test if their NULL. If they are not NULL in MySQL, you will just resubmit the same data to your db. Like this:
if ($demo_image_from_db!=NULL) $demo_image = $demo_image_from_db;
It is possible that there is also a MySQL native function for updating only when NULL - I've heard of COALESCE but I don't exactly know how to use it - that would be definitely the simplest way to do it.

why isnt this php working, i get undefined index...?

I am trying to upload an image to the server.
I hava a form with a couple of inputs...
INSIDE this form, I have an Iframe which contains another form for the upload, this because I dont want the original form to submit().
The original form basically:
<form> ...... bla bla bla alot of inputs....<iframe src="pic_upload.html"></iframe></form>
Here is pic_upload.html:
</head>
<body><form name="pic_form" id="pic_form" action="bincgi/imageUpload.php" method="post" target="pic_target"><input name="pic_file" type="file" id="pic_file" size="35" onchange="this.form.submit();"></form><div id="pic_target" name="pic_target" style="width:80px; height:80px;"></div></body>
</html>
Here is imageUpload.php:
<?php
$destination_path = getcwd().DIRECTORY_SEPARATOR;
//echo $destination_path;
$result = 0;
$target_path = $destination_path . basename($_FILES['pic_file']['name']);
if(#move_uploaded_file($_FILES['pic_file']['tmp_name'], $target_path)) {
$result = 1;
}
?>
I get this error: Undefined index: pic_file on line 5 in imageUpload.php
ALSO, if I get this to work, is there a good way to display the uploaded image inside the target of the form?
Thanks alot!
PS: I will add javascript to the tags because maybe thats what I need here!
Don't forget about form attribute
enctype="multipart/form-data"
The form needs to be like this
<form enctype="multipart/form-data" action="__URL__" method="POST">
Check out this PHP.net documentation for more information.
You first need to test if $_FILES has an item with the key pic_file. So use the isset function to do so:
$destination_path = getcwd().DIRECTORY_SEPARATOR;
//echo $destination_path;
$result = 0;
if (isset($_FILES['pic_file'])) {
$target_path = $destination_path . basename($_FILES['pic_file']['name']);
if (#move_uploaded_file($_FILES['pic_file']['tmp_name'], $target_path)) {
$result = 1;
}
}

Categories