I have created a PHP programm which allows to load a random .json file on my computer. When I select the file I want to display, I get the data from the selected .json file. At the beginning, I used a default file which I replaced with a variable. Here is the PHP code :
<?php
$uploaddir = 'uploads/';
$uploadfile = $uploaddir . basename($_FILES['file']['name']);
$file_test = explode('.', $_FILES['file']['name']);
$file_ext= strtolower(end($file_test));
$expensions = array(".json");
if(in_array($file_ext,$expensions)=== false){
$errors[]="extension not allowed, please choose a DBC or an XML file.";
}
if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
echo "<div style='font-size: 150%;'>". "File is valid, and was successfully uploaded.\n"."</div>";
} else {
echo "<div style='font-size: 150%;'>". "Oops, It seems you haven't uploaded a file ! Please make sure you have selected a .json file\n "."</div> <br>";
echo "<div style='font-size: 150%;'>". "Returning to Home...\n "."</div>";
header("Refresh: 3,URL=upload_file.php");
exit();
}
echo basename($_FILES['file']['name']);
?>
<?php
header("Refresh: 2,URL=json_content_extended.php?filename=".$uploadfile);
exit();
?>
This file contains the code where I declared the requested value :
<?php
$json_file = file_get_contents($_REQUEST["filename"]);
$jfo = json_decode($json_file, true);
?>
And here is the HTML part :
<!DOCTYPE html>
<html>
<head>
<title>Menu</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<form action="upload.php" method="POST" enctype="multipart/form-data" >
<div class="test">
<input type="file" accept=".json" name="file"/>
<button class="up" name="click" class="click">Submit file</button>
</div>
</form>
</body>
</html>
This is just an example ! What I actually want to do is the same thing in Javascript. I started the script with a default file, but now I would like to replace this file (default.json) with a variable. I use $.getJson. Here is the code :
$(document).ready(function() {
var files = ["default.json"];
$.getJSON(files, function(json) {
var tr0, tr1, tr2, tr3, tr4, tr5, tr6, tr7, tr8, tr9;
tr0 = $('<tr/>');
tr0.append("<td>" + '<input class="expand" name="bt0" type="button" value="+" />' + "</td>");
tr0.append("<td>" + json.messages[0].id + "</td>");
tr0.append("<td>" + json.messages[0].name + "</td>");
tr0.append("<td>" + json.messages[0].is_extended_frame + "</td>");
I wonder if there is somehow a possibility to set a variable instead of the file name. I would like to do the same thing I did in the PHP example, but this time in javascript.
Related
I try to make a website where people will have option to upload some files(excel, pdf etc.) and images. When they refresh the page I want them to see those files and have an option to download them.
I tried to google this for a long time and I am still not able to make it work. I read about bytea or blob option tried both. I even read and thought about using server file system.
This is as the far I've got.
<?php
$db = new PDO("pgsql:host=localhost;port=5432;dbname=name;user=user;password=pass");
if (isset($_POST["insert"])) {
$target_file = $_FILES["file"]["tmp_name"];
$img = fopen($target_file, 'r');
$data = fread($img, filesize($target_file));
//$file = pg_escape_bytea($data);
//$file = pg_escape_bytea(addslashes(file_get_contents($_FILES["image"]["tmp_name"])));
$sql = 'INSERT INTO test (data) VALUES (?)';
$ISp_Res = $db->prepare($sql);
$ISp_Res->bindParam(1, $data, PDO::PARAM_LOB);
$ISp_Res->execute();
}
?>
<html>
<head>
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br/><br/>
<div class="container" style="width:500px;">
<h3 align="center"></h3>
<br/>
<form method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info"/>
</form>
<br/>
<br/>
<?php
$query = "SELECT * FROM test ORDER BY id DESC";
$db = new PDO("pgsql:host=localhost;port=5432;dbname=name;user=user;password=pass");
$result = $db->prepare($query);
$results = $result->execute();
$results = $result->fetchAll(PDO::FETCH_ASSOC);
foreach ($results as $row) {
ob_start();
fpassthru($row['data']);
$dat = ob_get_contents();
ob_end_clean();
//echo (base$row['data']);
//$dat = stream_get_contents($row['data']);
$dat = pg_unescape_bytea($dat);
//$dat = "data:image/png;base64," . base64_encode($dat);
//echo "<img src='" . $dat . "'";
echo '<a href="'.$dat .'" download>You can download here '.$row['id'].'</a><br>';
}
?>
</div>
</body>
</html>
Now I was able to display an image on my website but it was in terrible quality. When I tried to download it there was a problem with corruption or missing parts.
Then I tried to unescape bytea from postgresql and I've got different problem that I cant download it at all.
As you can see in comment lines I tried some different things even combine some of them.
PS: I am an amateur so any comment will be helpful.
Its my first post so I am sorry If I broke any rules here.
EDIT:
Table I am trying to upload files.
CREATE TABLE public.test
(
id integer NOT NULL,
data bytea,
CONSTRAINT test_pkey PRIMARY KEY (id)
)
I am trying pass a parameter in action tag in form, just the way I am doing in href tag but this isn't working can I know why? or should I just use a href tag in form, will that overwrite action in form?
Here is my code:
<!DOCTYPE html>
<html lang="en">
<?php
$ty=$_GET['param'];
$name=$_GET['param1'];
if($ty=='teacher')
{
$web = "<a href='teacherrepute.php?a=$name'>My repute score</a>";
$rep = "<a href='teacherreported.php?a=$name'>My reported sites</a>";
$blk = "<a href='newblocktryteacher.php?a=$name'>Block this site</a>";
$unblk = "<a href='newtryunblockteacher.php?a=$name>Unblock this site";
}
else
{
$web = "<a href='pupilrepute.php?a=$name'>My repute score</a>";
$rep = "<a href='pupilreported.php?a=$name'>My reported sites</a>";
$blk = "<a href='newblocktrypupil.php?a=$name'>Block this site</a>";
$unblk = "<a href='newtryunblockpupil.php?a=$name>Unblock this site";
}
// $type=$_GET['param2'];
$courseA='A';
$courseB='B';
?>
<body>
<?php echo $rep; ?>
<FORM action = <?php echo $blk; ?> method ="POST";>
Block : <input type ="text" name = "url" /></br>
<br>
<input type="submit" value="block" />
<br>
</FORM>
</body>
</html>
1) As you already creating link based on condition then you can directly echo that variable inside markup. e.g.
<?php echo $rep; ?>
2) Instead of passing html in form action just you pass that script name. e.g
newblocktryteacher.php?a=somename or newblocktrypupil.php?a=somename
Based on these two points your code will be
<!DOCTYPE html>
<html lang="en">
<?php
$ty=$_GET['param'];
$name=$_GET['param1'];
if($ty=='teacher')
{
$web = "<a href='teacherrepute.php?a=$name'>My repute score</a>";
$rep = "<a href='teacherreported.php?a=$name'>My reported sites</a>";
$blk = "newblocktryteacher.php?a=$name";
$unblk = "<a href='newtryunblockteacher.php?a=$name>Unblock this site";
}
else
{
$web = "<a href='pupilrepute.php?a=$name'>My repute score</a>";
$rep = "<a href='pupilreported.php?a=$name'>My reported sites</a>";
$blk = "newblocktrypupil.php?a=$name";
$unblk = "<a href='newtryunblockpupil.php?a=$name>Unblock this site</a>";
}
// $type=$_GET['param2'];
$courseA='A';
$courseB='B';
?>
<body>
<?php echo $rep; ?>
<form action="<?php echo $blk; ?>" method="POST">
Block : <input type="text" name="url" /></br>
<br>
<input type="submit" value="block" />
<br>
</form>
</body>
</html>
Your $blk isn't formatted in a way proper for <form>:
$blk = "<a href='newblocktryteacher.php?a=$name'>Block this site</a>";
<FORM action = <?php echo $blk; ?> method ="POST";>
Assuming $name is bob in this example:
<FORM action = <a href='newblocktryteacher.php?a=bob'>Block this site</a> method ="POST";>
As you can see, this is not correct. All you need is the URL itself. Also, remove the semicolon after "POST".
Your $blk is not a valid action form, because it's a <a> tag(link). So, $blk should be newblocktrypupil.php?a=$name' instead.
Actually i want to print the content with below code sample.
$html having my all HTML which i want to print without render a View in Browser and without print/show in browser.
I am trying to find a Same method as window.print(); works. But need in PHP. I don't want to show all the HTML in Browser.
Is there any method or Trick ?
Any suggestion can help me lot.
Thank you.
My Sample Code:
$arr = array('one','two','three','four','five');
$html = "<div style='background:red;color:black;'>";
foreach($arr as $value){
$html .= $value.'<br />';
}
$html .= "</div>";
// print code to print $html content as same as JS window.print() works.
<script type="text/javascript">
function PrintDiv() {
var divToPrint = document.getElementById('divToPrint');
var popupWin = window.open('', '_blank', 'width=300,height=300');
popupWin.document.open();
popupWin.document.write('<html><body onload="window.print()">' + divToPrint.innerHTML + '</html>');
popupWin.document.close();
}
</script>
<div id="divToPrint" style="display:none;">
<div style="width:200px;height:300px;background-color:teal;">
<?php echo $html; ?>
</div>
</div>
<div>
<input type="button" value="print" onclick="PrintDiv();" />
</div>
I have a form in html:
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
and I want to get the value of this input in php without submitting it in a form.
this is my javascript:
var pName= null;
$(document).ready(function(){
$('img').click(function(){
pName= $(this).attr("name");
console.log(pName);
});
});
My php:
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
what I want is. you click on the picture,
1.the value of the name attribute of the picture is going to be saved into the variable pName (javascript),
2.it then goes into the form and changes the value of the form to the variable pName (javascript),
3.php picks up the value of the form (which should now be equal to pName),
4.then stores it into a variable $pName (php).
5.I also want $pName (php) to be globally used throughout all the pages of the website.
edit
this is my index page:
<?php
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
$query="SELECT * FROM project limit 5 ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="ppo.js"></script>
<link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="bgNav">
<div id="login">
Register
Log in
</div>
<nav id="nav">
Home
</nav>
</div>
<h2 class="titlePage">Home</h2>
<div id="bgTile">
<?php
while($row = mysqli_fetch_array($results))
{
$project = $row["name"];
echo nl2br("<a href='project.php'>" ."<img name=\"$project\" width='100px' alt='Procject name' height='100px' class='tile' src=". $row['image'] ."/>". "</a>");
}
?>
<div class="tile" id="tileM"><h2>Meer</h2></div>
</div>
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
</body>
</html>
what I want: click on the image then you get sent to the project page where (php) $pName is equal to the value of (javascript) pName
project page:
<?php
$newRecord = null;
$pName = isset($_POST['pNameChange']) ? $_POST['value'] : '';
$db_connection = mysqli_connect('localhost','root','',"project_online_planner");
if (!$db_connection){
die('Failed to connect to MySql:'.mysql_error());
}
//insert into database
if(isset($_POST['insertComments'])){
include('connect-mysql.php');
$username = $_POST['username'];
$comment = $_POST['comment'];
$sqlinsert = "INSERT INTO user_comments (username, comment, project) VALUES ('$username', '$comment', '$pName')";
if (!mysqli_query($db_connection, $sqlinsert)){
die('error inserting new record');
}
else{
$newRecord = "1 record added";
}//end nested statement
}
//text from database
$query="SELECT * FROM user_comments where project = '$pName' ";
$results = mysqli_query($db_connection,$query);
$intro=mysqli_fetch_assoc($results);
$query2="SELECT * FROM project where name = '$pName' ";
$results2 = mysqli_query($db_connection,$query2);
$intro2=mysqli_fetch_assoc($results2);
?>
<!DOCTYPE HTML>
<html>
<head>
<title>Project planner online</title>
<script src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript" src="ppo.js"></script>
<link rel="stylesheet" href="ppo.css"/>
</head>
<body>
<div id="intro">
</div>
<div id="bgNav">
<nav id="nav">
Home
<a class="rightNav" href="register.php">Register</a>
<a class="rightNav" href="login.php">Log in</a>
</nav>
</div>
<div id="projectTile">
<span id="statusCheck"><?php print_r($intro2["status"]); ?></span>
<h2 id="prTitle"><?php print_r($intro2["name"]); ?></h2>
<div id="prPic"><img width="300" height="200" src="<?php print_r($intro2["image"]); ?>"></div>
<div id="prDescription"><?php print_r($intro2["description"]); ?></div>
</div>
<div id="comments">
<?php
while($row = mysqli_fetch_array($results))
{
echo nl2br("<div class='profile_comments'>" . $row['username'] . "</div>");
echo nl2br("<div class='comment_comments'>" . $row['comment'] . "</div>");
}
?>
</div>
<div id="uploadComments">
<form method="post" action="project.php">
<label for="name"><input type="hidden" name="insertComments" value="true"></label>
<fieldset>
<legend>comment</legend>
<label>Name:<input type="text" id="name" name="username" value=""></label><br/>
<label>Comments: <textarea name="comment" id="comment"></textarea></label>
<input type="submit" value="Submit" id="submitComment">
</fieldset>
</form>
</div>
<?php
echo $newRecord;
?>
<form>
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
</body>
</html>
HTML:
do you have more then 1 image on page? its better if you add ID in image. No need for form and hidden fields for what you want done.
make sure your img has ID like <img id="imageID"...
JavaScript:
var pName= null;
$(document).ready(function(){
$('#imageID').click(function(){
pName= $(this).attr("name");
$.post("project.php", { pNameChange: pName },
function(data) {
// do something here.
});
});
});
above code should work as expected. Now in project.php > $_POST['pNameChange'] should receive the value of pName (image's name attr).
I don't understand what you want when you said $pName available globally on all pages. Please elaborate further, may be look into storing it as cookie/session?
EDIT:
Consider using session to pName value... by simple starting/resuming session in start of file:
<?PHP
session_start();
and then...
to set/update value:
if(isset($_POST["pNameChange"]))
$_SESSION["pName"] = $_POST["pNameChange"];
and then use $_SESSION["pName"] instead of $pName on all pages.
Try Ajax method in jQuery , hope it solves your problem
https://api.jquery.com/jQuery.ajax/
or
https://api.jquery.com/jQuery.post/
Actually, you do not need AJAX for this, all your index.php does it passes the image's name to project.php so try:
In index.php:
<form name='form1' method="post" action='project.php'> <!-- form attributes given -->
<label><input type="hidden" name="pNameChange" value=""></label>
</form>
Javascript:
var pName= null;
$(document).ready(function(){
$('img').click(function(){
//onclick of image, we will save the image name into the hidden input
//and submit the form so that it goes to project.php
$('input[name="pNameChange"]').val($(this).attr("name"));
$('form1').submit()
});
});
And in your project.php:
//now project.php can get the posted value of 'pNameChange'
//There is no input field with `name`->`value`, so $_POST['value'] is invalid.
$pName = isset($_POST['pNameChange']) ? $_POST['pNameChange'] : '';
And if you need this value across multiple pages, global will not work, use sessions.
ok this "additional" answer is to focus on session only. use the codes for client-end from my previous answer and try this on server-end.
index.php Page:
<?php
session_start();
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : '';
project.php Page:
<?php
session_start();
$newRecord = null;
$pName = isset($_SESSION['pNameChange']) ? $_SESSION['pNameChange'] : null;
if(is_null($pName) && isset($_POST['pNameChange'])) {
$_SESSION['pNameChange'] = $_POST['pNameChange'];
$pName = $_POST['pNameChange'];
}
hope it helps
I have some HTML Template and I want show them in iFrame, some of this Template have 2 to 11 colors variety.
folder name ex.
1
2
3
3-1
3-2
3-3
3-4
3-5
4
5
6-1
6-2
7
and more...
I have a botton for show NEXT template.
I want use is_dir in php to check if directory 1 or 3-2 is available then show it.
<?php
$id = $_GET['id'];
$c=$id+1;
$c1=$c."-1";
$xm=$c;
$xm1=$c1;
if (is_dir($xm)) {
$c=$c;
}
if (is_dir($xm1)) {$c=$c1;}
?>
<div id="header-bar">
<form method="get" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="id" value="<?php echo $c ?>">
<input type="submit" value="NEXT">
</form>
</div>
<iframe src="http://barg.ir/demo/<?php echo $id; ?>"></iframe>
Question1: I can show folder 3-1 but I cant show folder 3-2 and 3-3 and..., how do this?
Question2: can coding with php array?
Question3: can coding with JavaScript? what is equal is_dir in javascript?
Why don't you look into using glob()? Put the following into the folder you want to get the information from:
// we'll call it grabber.php
<?php
$files = glob('*', GLOB_ONLYDIR); sort($files, SORT_NATURAL);
?>
// now you can include grabber.php in your form file
<?php
session_start(); include_once 'PATH/grabber.php'; $end = count($files)-1;
<div id='header-bar'>
<form method='post' action='<?php echo $_SERVER['PHP_SELF']; ?>'>
<input type='submit' value='BACK' name='back' />
<input type='submit' value='NEXT' name='next' />
</form>
if(isset($_POST['back'])){
$_SESSION['fileNum']--;
if($_SESSION['fileNum'] < 0)$_SESSION['fileNum'] = $end;
}
elseif(isset($_POST['next'])){
$_SESSION['fileNum']++;
if($_SESSION['fileNum'] > $end)$_SESSION['fileNum'] = 0;
}
else{
$_SESSION['fileNum'] = 0;
}
$f = $files[$_SESSION['fileNum']];
echo " <iframe src='http://barg.ir/demo/$f'></iframe>".
'</div>';
?>
Obviously PATH needs to be changed.
Better yet use JavaScript:
// You'll still need `grabber.php` in the same location as before, only now
// we'll actually make the PHP page into a String for JavaScript usage, like:
<?php
$dirs = glob('*', GLOB_ONLYDIR); sort($dirs, SORT_NATURAL);
$dirsJS = implode("', '", $dirs); // implode into a String for JavaScript Array
echo "//<![CDATA[
var doc = document, bod = doc.body;
bod.className = 'js'; // use .njs class in CSS for users without JavaScript
function E(e){
return doc.getElementById(e);
}
function direct(backId, nextId, iframeId, iframeSrcBase){
var dirs = ['$dirsJS'];
var dl = dirs.length-1, n = 0, f = E(iframeId), s = iframeSrcBase;
f.src = s+dirs[0];
E(backId).onclick = function(){
if(--n < 0)n = dl;
f.src = s+dirs[n];
}
E(nextId).onclick = function(){
if(++n > dl)n = 0;
f.src = s+dirs[n];
}
}
//]]>";
?>
/*
Now back to your main page. I like XHTML, but you can use whatever.
The reason for JavaScript is to avoid scrolling issues and page flashing
This is your main page again without as much PHP. There's no need to
include the other file in PHP, or use a session. We use the `script`
tag instead. Pay attention:
*/
<?php
echo "<!DOCTYPE html>
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>
<head>
<meta http-equiv='content-type' content='text/html;charset=utf-8' />
<style type='text/css'>
#import 'yourCSS.css';
</style>
</head>
<body class='njs'>
<div id='header-bar'>
<form method='post' action='{$_SERVER['PHP_SELF']}'>
<input type='button' value='BACK' name='back' id='back' />
<input type='button' value='NEXT' name='next' id='next' />
</form>
<iframe id='ifr' src=''><noscript>Your Browser Does Not Support JavaScript</noscript></iframe>
</div>
<script type='text/javascript' src='PATH/grabber.php'></script>
<script type='text/javascript'>
direct('back', 'next', 'ifr', 'http://barg.ir/demo/');
</script>
</body>
</html>";
?>
Once again, this time in the script tag, change PATH accordingly.