I have a php file and I have created 2 buttons get and set in the file.
I want to access Get.php file when I click get
<?php
$file = "xxx.json";
include 'Get.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
and Set.php file when I select set button.
<?php
$file = "xxx.json";
include 'Set.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
My file visual.php file contents are:
<!DOCTYPE html>
<meta charset="utf-8">
<?php
$file = "xxx.json";
include 'Get.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
<style>
right {
display:table-cell;
vertical-align:top;
width:300px;
padding:0 5px;
}
<?php
$color=include('Color.php');
echo $color;
?>
</style>
<body>
<div id=tt>
<button type="submit" onclick="get()"> <b>get</b></button>
<button type="submit" onclick="set()"> <b>set</b></button>
</div>
<div id=graph>
<script src="ll.js"></script>
<script src="visual.js"></script>
<script type="text/javascript">
window.onload = function(){
}
<?php
$link=include('Link.php');
echo $link;
?>
</script>
</div>
<body>
I am not sure how can I get the contents for Get.php file and Set.php file. I know that I can call ajax calls. But in that case only I can get the contents of the Get.php or Set.php files.
But how can I also make other data shown below execute in sequential order.
<?php
$file = "xxx.json";
include 'Get.php';
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
?>
I am new to php. Thanks for all your help.
Bes way, is using standard html methods: name-value for form elements
<body>
<form method="GET">
<button type="submit" name="event" value="get"> <b>get</b></button>
<button type="submit" name="event" value="set"> <b>set</b></button>
</form>
<body>
And the php code:
$file = "xxx.json";
switch ($_GET['event'])
{
case 'get': include 'Get.php'; break;
case 'set': include 'Set.php'; break;
}
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($file,$output);
Dmitriy's answer is pretty easy, and clean looking. I like.
Ive made a little longer example, utilizing a class aswell, and commented it throughoutly for you to perhaps learn a little or two. Hope it helps!
<?php
class HandleFile {
protected $file;
//The construct is called, when the object is created. We request the file here.
public function __construct($file = null) {
//Lets check if the file variable is set or not.
if( !is_null($file) ) {
//Lets check if the file actually exists
if( file_exists($file) ) {
//If the file exists, set the class variable.
$this->file = $file;
} else {
//If the file does not exist. Throw an exception
throw new Exception("Construct:: The file " . $file . ", does not exist.");
}
} else {
//If the file variable is not set, throw an exception.
throw new Exception("Construct:: No file specified.");
}
}
//This function will do our actual logic.
public function doAction($fileToInclude) {
//First, check if the file to include exists.
if( file_exists($fileToInclude) ) {
//Include it
include($fileToInclude);
ob_start();
formatPara("0");
$output = ob_get_clean();
file_put_contents($this->file,$output);
} else {
//If it does not exist. Throw exception.
throw new Exception("doAction:: File " . $fileToInclude . ", does not exist.");
}
}
}
//Try/catch. Tries the action and if an error is trown, catch it and output the message.
try {
$Handler = new HandleFile("xxx.json");
} catch(Exception $e) {
print $e->getMessage() . "<br>";
}
//Define a helper variable
$action = null;
//If the GET parameter "get" is set, do a get action
if( isset( $_GET['get'] ) ) {
$action = "Get.php";
//If the GET parameter "post" is set, do a post action.
} elseif( isset( $_GET['post'] ) ) {
$action = "Post.php";
}
//If our helper variable has changed, there must be an action to do.
if( !is_null($action) ) {
//Try/catch. Tries the action and if an error is trown, catch it and output the message.
try {
$Handler->doAction($action);
} catch(Exception $e) {
print $e->getMessage() . "<br>";
}
}
?>
<body>
<form action="" method="GET">
<button type="submit" name="get" value="yes"> <b>get</b></button>
<button type="submit" name="post" value="yes"> <b>set</b></button>
</form>
<body>
You're calling a function which isn't set...
why don't you use $_POST
to with 2 different forms
1 hidden input contains the id type
if the type is get then include the get
if the type is set then include the set
this is just an example tho'
Related
new to forum, AJAX and JQuery. A little experience of PHP and JS.
I'm trying to present a long series of questions (400+) one by one in an input text field on a form with 2 submit buttons labelled "True" and "False". I need one question to be presented at a time, then record the True or False result as (1 or -1) sequentially into another text file. I cannot refresh the input field with the next question after 'Submit'. I believe that AJAX would be the answer.
This code is the first effort: (any later efforts are more complicated, but don't work any better) it opens the questions file (CPXQ.dat) into an indexed array, then places the first question into the input text field. When either of the submit buttons are pressed, the result is POSTed to data.cpx, and the next question appears, but it won't continue thereafter. I have tried various PHP loops and some javascript, but these don't work, either looping through immediately to the last question, or getting stuck in the loop. (The php includes just contain CSS and JQuery source.)
I'd also like to prevent the user from being able to go back over any of the questions, but that may be a query for another day!
Any advice much appreciated, and apologies if not clear. Happy to provide any further info.
<div class="container">
<?php include("top.php"); ?>
<div class="intro">
<p><h1>CPI TEST</h1></p>
<?php
$i = 0;
//file in to an array
$lines = file("CPXQ.dat");
?>
<?php
if(isset($_POST['submitT'])) {
//echo $_POST['submitT'];
$data="1";
//echo $data;
$fp = fopen('data.cpx', 'a') or die("Unable to open file!");
fwrite($fp, PHP_EOL);
fwrite($fp, $data);
fclose($fp);
++$i;
}
if(isset($_POST['submitF'])) {
//echo $_POST['submitF'];
$data="-1";
//echo $data;
$fp = fopen('data.cpx', 'a') or die("Unable to open file!");
fwrite($fp, PHP_EOL);
fwrite($fp, $data);
fclose($fp);
++$i;
}
?>
<form method = "post" action = "CPI_Test.php">
<input type="text" name="question" value="<?php echo $lines[$i];?>">
<input type="submit" name="submitT" value="True">
<input type="submit" name="submitF" value="False">
</form>
</div>
</body>
Here's the code for the preliminary page collecting user details:
<!DOCTYPE html>
<html>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>PPCS CPI Information</title>
<?php include("head.php"); ?>
</head>
<body>
<?php
// define variables and set to empty values
$initdataErr = $surnamedataErr = $agedataErr = $gendataErr = "";
$initdata = $surnamedata = $agedata = $gendata = $codata = "";
function test_input(&$surnamedata) {
$surnamedata = trim($surnamedata);
$surnamedata = stripslashes($surnamedata);
//$data = htmlspecialchars($data);
$surnamedata = preg_replace('/\s+/', '', $surnamedata);
return $surnamedata;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST['initdata'])) {
$initdataErr = "Initials are required";
} else {
$initdata = test_input($_POST['initdata']);
// check if name only contains letters and whitespace
if (!preg_match("/^[A-Z- ]*$/",$initdata)) {
$initdataErr = "Please use capital letters without spaces only";
}
}
if (empty($_POST['surnamedata'])) {
$surnamedataErr = "Surname is required";
} else {
$surnamedata = test_input($_POST['surnamedata']);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Z-' ]*$/",$surnamedata)) {
$surnamedataErr = "Please use letters only";
}
}
if (empty($_POST['agedata'])) {
$agedataErr = "Age is required";
} else {
$agedata = test_input($_POST['agedata']);
// check if name only contains letters and whitespace
if (!preg_match("/^[0-9]*$/",$agedata)) {
$agedataErr = "Only numbers and white space allowed";
}
}
if (empty($_POST['gendata'])) {
$gendataErr = "Gender is required";
}
}
?>
<div class="container">
<?php include("top.php"); ?>
<br><h1>CPI TEST INFORMATION</h1><br>
<b>Please fill in the form below carefully</b>
<p><span class="error">* required field</span></p>
<br>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Initials: <span class="error">* <?php echo $initdataErr;?></span> <br>
<input type="text" name="initdata" value="<?php echo $initdata;?>"><br>
<br>
Surname: <span class="error">* <?php echo $surnamedataErr;?></span> <br>
<input type="text" name="surnamedata" value="<?php echo $surnamedata;?>" ><br>
<br>
Company (Optional):<br>
<input type="text" name="codata" value="<?php echo isset($_POST["codata"]) ? $_POST["codata"] : '';?>" ><br>
<br>
Age in Years: <span class="error">* <?php echo $agedataErr;?></span><br>
<input type="text" name="agedata" maxlength="2" min="0" max="99" step="1" pattern="[0-9]{2}"value="<?php echo $agedata;?>"><br>
<br>
Gender: <span class="error">* <?php echo $gendataErr;?></span><br>
<select name="gendata">
<option value="">Select...</option>
<option value="m" <?php echo (isset($_POST['gendata']) && $_POST['gendata'] == 'm') ? 'selected' : ''; ?>>Male</option>
<option value="f" <?php echo (isset($_POST['gendata']) && $_POST['gendata'] == 'f') ? 'selected' : ''; ?>>Female</option>
</select>
<br>
<input type="submit" name="submit" value="Submit">
</form>
</div>
</body>
</html>
<?php
if(isset($_POST['submit'])){
// Fetching variables of the form which travels in URL
$initdata = $_POST['initdata'];
$surnamedata = $_POST['surnamedata'];
$codata = $_POST['codata'];
$agedata = $_POST['agedata'];
$gendata = $_POST['gendata'];
if($initdata !=''&&(preg_match("/^[A-Z]*$/",$initdata))
&& $surnamedata !='' && (preg_match("/^([A-Za-z \-]+(?:\'|�*39;)*)*[A-Za-z \-]+$/",$surnamedata)) && $agedata !='' && (preg_match("/^[0-9]*$/",$agedata)) && $gendata !='')
{
date_default_timezone_set("Europe/London");
//^['\a-zA-Z]*$/ This is the most recent
test_input($surnamedata);
$_POST['surnamedata'] = ucwords($_POST['surnamedata']);
$data = '"' . $_POST['initdata'] . ' ' . stripslashes($_POST['surnamedata']) . '","' . $_POST['agedata'] . '","'. $_POST['gendata'] .'","' . $_POST['codata'] . '","' . '","'. '","'. date("d/m/Y"). '","'. date("H:i:s"). '","';
//Create CPX filename
$fn = $_POST['initdata'] . $_POST['surnamedata'];
$fn = preg_replace('/\PL/u', '', $fn);
$fn = strtoupper($fn);
$fn = $fn . "XXXXXX";
$fn = substr($fn,0,8);
echo "$fn";
echo "$data";
//Create temp file for CPX filename
$fp = fopen($fn . '.temp', 'a') or die("Unable to open file!");
fwrite($fp, $fn);
fclose($fp);
//Create CPX file
$fp = fopen($fn . '.cpx', 'a') or die("Unable to open file!");
fwrite($fp, $data);
//Append new line
//fwrite($fp, "\ntest");
fclose($fp);
// Redirect
/header("Location:/CPI_Form_Trial/instructions.php");
}
else{
?>
<br><span class = "error"><?php echo "Please make sure that you have filled in all required fields and click 'Submit' again";?></span> <?php
}
}
?>
Using AJAX (fetch) is ideally suited to this type of problem where you do not wish to refresh the screen and want to present new data after submitting a http request. The following single page application shows how you might accomplish your stated goal but it does not take into account a couple of possible issues which are:
[a] multiple users participating in the questionnaire simultaneously
[b] a user abandoning the questionnaire and restarting, once or more than once.
The issues mentioned could be negated by using a database to store answers and assigning the users unique identifiers (ie: user id, username) which is used when sending the ajax request.
The demo that follows will write, to the answerfile, either 1 or 0 ( which is more common than -1 for false ) alongside the question line number ( which is sort of the ID )
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['action'] ) ){
ob_clean();
$file='CPXQ.dat';
$answerfile='data.cpx';
$lines=file( $file );
switch( $_POST['action'] ){
case 'start':
header('Content-Type: text/html');
exit( $lines[0] );
break;
case 'question':
$id=(int)$_POST['id'];
# increment ID value
$id++;
$question=isset( $lines[ $id ] ) ? $lines[ $id ] : false;
if( $question && $id < count( $lines ) ){
# log the current answer
file_put_contents( $answerfile, sprintf( 'q:%s,a:%s', $id, $_POST['answer'] ) . PHP_EOL, FILE_APPEND );
# the json payload
$data=array(
'id' => $id,
'question' => $question
);
} elseif( !$question && $id==count( $lines ) ){
# log the final answer
file_put_contents( $answerfile, sprintf( 'q:%s,a:%s', $id, $_POST['answer'] ) . PHP_EOL, FILE_APPEND );
$data=array(
'id' => 0,
'question' => 'End of questionnaire'
);
}
header('Content-Type: application/json');
exit( json_encode( $data ) );
break;
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>Questions, questions, questions...</title>
</head>
<body>
<!--
a basic form: The question is rendered within the `fieldset`
element. Both buttons use datasets, the data-id refers to the
question number (line from source file) and data-value is the
boolean value indicating answer value.
-->
<form name='questions' method='post'>
<fieldset></fieldset>
<div>
<input type='button' data-value=1 data-id=0 value='True' />
<input type='button' data-value=0 data-id=0 value='False' />
</div>
</form>
<script>
const fs=document.querySelector('fieldset');
/*
When the page loads we fetch the first question ( ie: first line in source file )
and display on the page. The action parameter helps the backend determine what stage
we are at.
*/
let fd=new FormData();
fd.set('action', 'start');
// make the request an show question
fetch( location.href, { method:'post', body:fd })
.then(r=>r.text())
.then(text=>{
fs.innerHTML=text;
});
/*
The delegated event handler processes button clicks and sends the
data-id ( ie: line number ) and answer to the backend processing script.
Here this is all done on the same page for convenience - for your case
it would be CPI_Test.php
*/
const clickhandler=function(e){
if( e.target.tagName.toLowerCase()=='input' && e.target.type=='button' ){
// set a different `action` so that the backend knows what to do
fd.set('action','question');
fd.set('id',e.target.dataset.id);
fd.set('answer',e.target.dataset.value);
// send the request and display new question
fetch( location.href, { method:'post', body:fd } )
.then( r=>r.json() )
.then( json=>{
fs.innerHTML=json.question;
// update the buttons so that they have the new id assigned ready for next click
// or disable ( or remove ) when the questionnaire is over.
document.querySelectorAll('[type="button"][data-value]').forEach( bttn=>{
if( Number( json.id ) !==0 ) bttn.dataset.id=json.id;
else bttn.disabled=true;
});
})
}
};
// add a delegated event handler to process button clicks
document.forms.questions.addEventListener( 'click', clickhandler );
</script>
</body>
</html>
A sample of the answerfile:
q:1, a:1
q:2, a:0
q:3, a:1
q:4, a:1
q:5, a:0
q:6, a:0
q:7, a:1
q:8, a:0
q:9, a:1
q:10, a:0
q:11, a:1
q:12, a:1
q:13, a:1
q:14, a:1
q:15, a:0
q:16, a:1
q:17, a:0
q:18, a:1
q:19, a:1
q:20, a:0
I hope it helps you arrive at a solution but as mentioned it would be more robust / reliable with a database rather than simple text file.
I need my page bargraph.html to get parameters like .../bargraph.html?di=xxxx&mn=yyyy and save the values of di and mn using a php script in a text file named cred.txt. The code I'm using for bargraph.html is
<body>
<?php
$mobile_num = $_GET["mn"];
$device_id = $_GET["di"];
$file_name = "cred.txt";
$location = "cred/".$file_name;
$text = $mobile_num."\n".$mobile_num;
$my_file = fopen($location, "w") or die("Unable to open file!");
fwrite($my_file, $text);
echo "response submitted successfully!";
fclose($my_file);
?>
</body>
The file named cred.txt is not created inside the cred/ directory and neither I get any errors. What am I doing wrong?
If the same thing can be done using JavaScript I'll use that instead of php for this purpose.
The question references bargraph.html - presumably the php code that you have is NOT on that page but a separate script? If that is the case then if you were to use exception handling to try to track down the issue it might help. Also, I have always found better success when using full paths as opposed to relative ones
<?php
if( isset( $_GET['mn'], $_GET['di'] ) ){
try{
$filename='cred.txt';
$mobile_num=filter_input( INPUT_GET, 'mn', FILTER_SANITIZE_STRING );
$device_id=filter_input( INPUT_GET, 'di', FILTER_SANITIZE_STRING );
/*
I have always found it is best to use a full path rather than relative
Change `path/to/` to the appropriate path
*/
$path=$_SERVER['DOCUMENT_ROOT'] . '/path/to/cred';
/* If the path does not exist, warn user */
if( !realpath( $path ) ){
throw new Exception( sprintf( 'Unable to find path: %s', $path ) );
}
/* Can the chosen directory be read? */
if( is_readable( $path ) && is_writable( $path ) ){
$file=$path . '/' . $filename;
#$text=$mobile_num . PHP_EOL . $mobile_num . PHP_EOL;
/* I think this is probably what you intended? */
$text=$device_id . PHP_EOL . $mobile_num . PHP_EOL;
$status=file_put_contents( $file, $text, FILE_APPEND | FILE_TEXT );
throw new Exception( $status ? sprintf('All good! Saved %s',$file) : sprintf('Error - unable to save %s',$file) );
} else {
/*
should set permissions if reading/writing of target folder failed
chmod($path,0777); etc
*/
throw new Exception( sprintf( 'The path %s is either not readable or writable',$path ));
}
}catch( Exception $e ){
exit( $e->getMessage() );
}
}
?>
Using a plain HTML page you could send an ajax request to the above PHP script ( in code below called bargraph.php )
<html>
<head>
<title>ajax-store credentials</title>
</head>
<body>
<form id='bg'>
<input type='text' name='mn' id='mn' placeholder='Mobile number: eg 0141 353 3874' />
<input type='text' name='di' id='di' placeholder='Device ID: eg yellow banana' />
<input type='button' id='bttn' value='Go' />
</form>
<script>
document.getElementById('bttn').onclick=function(e){
var mn=document.getElementById('mn').value;
var di=document.getElementById('di').value;
if( mn != '' && di != '' ){
var xhr=new XMLHttpRequest();
xhr.onload=function(r){
document.getElementById('status').innerHTML=this.response;
};
xhr.onerror=function(r){
document.getElementById('status').innerHTML=err.message;
};
xhr.open('GET','?mn='+mn+'&di='+di,true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send();
}
}
</script>
<div id='status'></div>
</body>
</html>
You can do like this.
$mobile_num = $_GET["mn"];
$device_id = $_GET["di"];
$file_name = "cred.txt";
$path = getcwd();
$location = $path.'/cred/'.$file_name;
$text = $device_id."\n".$mobile_num;
$my_file = fopen($location, "w") or die("Unable to open file!");
fwrite($my_file, $text);
echo "response submitted successfully!";
fclose($my_file);
You need to give write permission on cred folder.
I'm trying to create a specific module to upload files.
I'm using this code:
Client side:
<?php
// No direct access
defined('_JEXEC') or die; $resposta =""; ?>
<form name="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file_upload" />
<input type="submit" name="submit_file" value="submit_file"/>
<input type="text" name="resposta" value=<?php echo $resposta; ?> />
</form>
My module:
<?php
defined('_JEXEC') or die;
include_once __DIR__ . '/helper.php';
//trigger the event
// Instantiate global document object
defined('_JEXEC') or die;
// Include the syndicate functions only once
require_once dirname(__FILE__) . '/helper.php';
$resposta = ModuploadfileHelper::getuploadfile($params);
require JModuleHelper::getLayoutPath('mod_upload_file');
?>
My helper:
<?php
class ModuploadfileHelper {
public static function getuploadfile($params) {
/*
* File upload example
*/
//Retrieve file details from uploaded file, sent from upload form
$file = JFactory::getApplication()->input->get('file_upload');
//Import filesystem libraries. Perhaps not necessary, but does not hurt
jimport('joomla.filesystem.file');
//Clean up filename to get rid of strange characters like spaces etc
$filename = JFile::makeSafe($file['name']);
//Set up the source and destination of the file
$src = $file['tmp_name'];
$dest = JPATH_COMPONENT . DS . "uploads" . DS . $filename;
if(!JFolder::exists($dest))
{
$mode = 0755;
JFolder::create($dest, $mode);
}
$resposta = null;
//First check if the file has the right extension, we need jpg only
if (strtolower(JFile::getExt($filename)) == 'jpg')
{
// TODO: Add security checks
if (JFile::upload($src, $dest))
{
$resposta = "Sucesso ao arquivar a imagem";
}
else
{
$resposta = "Insucesso ao arquivar a imagem";
}
}
else
{
$resposta = "O ficheiro não é uma imagem";
}
return $resposta;
}
}
?>
First question: Does something like this work?
Second question: How to perform a trigger for the module to work?
Thirteenth question: How to pass the module to ajax?
I have something like this:
Module code:
<?php
defined('_JEXEC') or die;
include_once __DIR__ . '/helper.php';
// Instantiate global document object
defined('_JEXEC') or die;
// Include the syndicate functions only once
require_once dirname(__FILE__) . '/helper.php';
$resposta = ModuploadfileHelper::getuploadfile($params);
defined('_JEXEC') or die;
include_once __DIR__ . '/helper.php';
// Instantiate global document object
$doc = JFactory::getDocument();
$js = <<<JS
(function ($) {
$(document).on('click', 'input[type=submit]', function () {
formdata = new FormData();
var file = this.files[0];
formdata.append("image", file);
$.ajax({
type : 'POST',
data : request,
success: function (response) {
$('.search-results').html(response);
}
});
return false;
});
})(jQuery)
JS;
$doc->addScriptDeclaration($js);
require JModuleHelper::getLayoutPath('mod_upload_file');
?>
Help me please.
It is possible, what you need to do, is to use the Joomla ajax interface.
See the documentation here: https://docs.joomla.org/Using_Joomla_Ajax_Interface
There is a full example of a module implementing this, that you can easily modify to adapt to file upload:
https://github.com/Joomla-Ajax-Interface/Ajax-Session-Module
I want to tranform a php array of string into html. My php and html code are in the same page.
I have $myvar that hold my array of string. I pass $myvar with POST and insert it to $ba.
My code needs to print on html page 3 line (in while loop).
But when I pass the $be, it writes me error message: "Notice: Undefined index: myvar" (in php code)
What do I need to repair so that my code prints to my screen all the 3 lines that I get from php?
my code:(php)
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
$myvar[]=fgets($handle);
$counter++;
}
}
}
$ba = implode("", $myvar);
my html code:
<form action="" method="POST">
<center>
<h1> My Search Engine </h1>
<input type = 'text' size='90' value='' name = 'search' > <br>
<input type = 'submit' name = 'submit' value = 'Search source code'>
</center>
</form >
<p> <?php echo $ba ?> </p>
Simply echo the mysql query on a function and call it on HTML as follows:
UPDATE: 3rd column will be an image wich route are stored on database, and 4th col will be an image eich only the name was stored on database (because we know the full route) as example:
<?php
function printOnHtml(){
include ("connection.php");
$sql = "SELECT * FROM foo;"
if ($result = connection()->query($sql)){
$rs = $result->fetch_array(MYSQLI_NUM);
while ($rs[0] != ''){
echo "first column: ".$rs[0]." second column: ".$rs[1]." image with full route on database: <img src='".$rs[2]."' alt=''> <br> if only the img name is stored cuz we know the route: <img src='img_route/".$rs[3]."' alt=''>";
$rs = $result->fetch_array(MYSQLI_NUM);
}
}
}
Then on HTML
<html>
blablabla
<body>
blablabla
<?php
printOnHtml();
?>
blablabla
</body>
</html>
Note that it have to be a .php file to call the php function (for example index.php)
I paste the connection php script i use in order if you need it:
<?php
function connection(){
if($mysqli = new MySQLi("localhost","user","password","database_name")) echo "OK"; else echo "KO";
mysqli_set_charset($mysqli, "utf8");
return $mysqli;
}
?>
i did it with mysqli fetch array, but you can do the same using fetch assoc if you want.
UPDATE2: If you stubborness makes you follow using a txt to store data (wich, if increase will fail when you get a some thousands line txt), modify this on your code:
$myvar='';
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
if(isset($myvar)){
$myvar=fgets($handle);
}
$counter++;
}
}
}
and i'm supposing that you declared $dir, $file and other vars properly.
You NEVER have to use vars without declaring it (as NULL at least). You only can do this if you ensured 100% that this var will get a value at this point.
You have to convert the array to string in a correct way using implode and <br> as a separator
Then just print it using php tags (as you are using both at the same page ) you can access the variable direct and print it using <?= $ba ?> or <?php echo $ba ; ?>
Code will be :
<?php
foreach ($docres as $key=>$filename) {
$counter = 0;
$file = $filename +1;
$handle = fopen($dir."/".$file.'.txt',"r");
if($handle)
{
while($counter < 3)
{
$myvar[]=fgets($handle);
$counter++;
}
}
}
$ba = implode("<br>", $myvar);
?>
<form action="" method="POST">
<center>
<h1> My Search Engine </h1>
<input type = 'text' size='90' value='' name = 'search' > <br>
<input type = 'submit' name = 'submit' value = 'Search source code'>
</center>
</form >
<p id="deatiles"> <?= $ba ?> </p>
I created a form, which includes an hidden input and its value is set by an function.
<?php
class Token {
public static function generate(){
return $_SESSION['token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
}
?>
This is called like this:
<input type="hidden" id="token" value="<?php echo Token::generate(); ?>">
I sent it via JavaScript/AJAX to another file (e.g. "form.php"), which contains something like:
<?php
session_start();
#require_once 'Token.class.php';
echo $_POST['token'] . " => " . $_SESSION['token']; // different tokens, why?
// $_POST['token'] is the one, that I want
// and so on...
?>
Why do the values change, when I type in: <?php echo $_SESSION['token']; ?> ?
This is my project stored on Dropbox
Because you are generating new one every time you are entering a site?
<?php
class Token {
public static function generate(){
if(isset($_SESSION['token']) && $_SESSION['token']) return $_SESSION['token'];
else return $_SESSION['token'] = base64_encode(openssl_random_pseudo_bytes(32));
}
}
?>
PS. You may want to use md5(uniqid()) instead.