Upload image and place cookie based on JSON variable in PHP - javascript

I'm trying to make a form work, with submitting from JavaScript and a variable from my JSON.The general idea is to upload the file to a folder, and define the path in a cookie. I'm working in PHP. Somehow I just can't make the if statement return TRUE.
My code looks like this:
From functions.php
function SaveSelfieCam () {
$currentQuiz = GetCurrentQuiz();
if (!empty($_FILES[$currentQuiz->id])) {
$myFile = $_FILES[$currentQuiz->id];
if ($myFile["error"] !== UPLOAD_ERR_OK) {
echo "<p>Der skete en fejl.</p>";
exit;
}
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
$i = 0;
$parts = pathinfo($name);
while (file_exists(QR_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
$success =
move_uploaded_file($myFile["tmp_name"],QR_DIR . $name);
if (!$success) {
echo "<p>Det lykkedes ikke at gemme filen.</p>";
exit;
}
if ($success) {
echo "Alt er godt!";
setcookie($currentQuiz->id, QR_DIR . $name);
chmod(QR_DIR . $name, 0644);
}
}
}
HTML Form (from my index.php)
echo "<form id='form' action='' method='post'><input id='selfieCam' class='quizCam' type='file' capture='user' accept='image/*' name='" . $currentQuiz->id . "' onchange='submitSelfie()'><label for='selfieCam'>Til kameraet</label></form></div>";
SaveSelfieCam ();
JavaScript (submitting form):
function submitSelfie() {
document.getElementById("form").submit();
}

try to add enctype='multipart/form-data' to your form as attribute-value like this
<form id='form' action='' method='post' enctype='multipart/form-data'>

Related

My javascript code result is blinking

When I am clicking on the Bengali button its showing data for few seconds and hiding it again, whereas I wrote the same code for the Assamese button, it displaying fine:
<script>
function be(){
var x= document.getElementById('ben');
if (x.style.display==='block'){
x.style.display='none';
}
else
{
x.style.display='block';
}
}
</script>
<button class= "button" onclick="be()">BENGALI</button>
<div id="ben">
<?php
$dir = '/home/test/data/Bengali/';
if (!isset($_POST['submit'])) {
if ($dp = opendir($dir)) {
$files = array();
while (($file = readdir($dp)) !== false) {
if (!is_dir($dir . $file)) {
$files[] = $file;
}
}
closedir($dp);
}
if ($files) {
echo '<form action="' . $_SERVER['PHP_SELF'] . '" method="post">';
foreach ($files as $file) {
echo '<input type="checkbox" name="files[]" value="' . $file . '" /> '
.
$file . '<br />';
}
}
}
?></div>
You call the function when you click on a submit button.
So the JS runs, then the form submits, and you load a new page.
The new page doesn't set the default styles to what they were before, so it has the effect of resetting the page.
As already mentioned, a new page is opening because a button has been clicked. The best way to solve this is by modifying your button like this:
<button class= "button" onclick="be()" type="button">BENGALI</button>
This prevents the form from submitting and runs your JavaScript function

Have description have a limit of the amount of characters on the page. PHP

Okay, so I'm working on a PHP site, I have descriptions of the product under the image, what I'm need to do is limit the amount of characters on the page and add a click here or.. For the viewers to be directed to that products page to see the full description. FYI very new to PHP, here is what I have so far. So question is do I use PHP or javascript or both and how do I do that ?
<?php
// Include need php scripts
require_once ("Includes/simplecms-config.php");
require_once ("Includes/connectDB.php");
include ("Includes/header.php");
if (!empty($_GET['cat'])) {
$category = $_GET['cat'];
$query = mysqli_query($db, "SELECT * FROM products WHERE category = '".$category."'");
} else {
$query = mysqli_query($db, "SELECT * FROM products");
}
if (!$query) {
die('Database query failed: ' . $query->error);
}
?>
<section>
<div id="productList">
<?php
$row_count = mysqli_num_rows($query);
if ($row_count == 0) {
echo '<p style="color:red">There are no images uploaded for this category</p>';
} elseif ($query) {
while($products = mysqli_fetch_array($query)){
$file = $products['image'];
$product_name = $products['product'];
$image_id = $products['id'];
$price = $products['price'];
$desc = $products['description'];
echo '<div class="image_container">';
echo '<a href="viewProduct.php?id=' . $image_id . '"><p><img src="Images/products/'.$file.'" alt="'.$product_name.'" height="250" /></p>';
echo $product_name . "</a><br>$" . $price . "<br>" . $desc;
echo '</div>';
if (is_admin()){
echo "<a href='deleteproduct.php'><button>delete</button></a>";
}
}
} else {
die('There was a problem with the query: ' .$query->error);
}
mysqli_free_result($query);
?>
</div>
</section>
<?php include ("Includes/footer.php"); ?>
using strlen and substr we can achieve this
$length = 150
$x = 'string';
if(strlen($x)<=$length)
{
echo $x;
}
else
{
$y=substr($x,0,$length) . '...';
echo $y;
}

Display alert or msgbox after successfully submission

Haii,
I like to display some msg or alert that say "Thank for submit" after user submit the form. How to do that? Where are the perfect location to put msg/alert code on my code?Here my insert data to mysql code.
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
$editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
if ((isset($_POST["MM_update"])) && ($_POST["MM_update"] == "form")) {
$updateSQL = sprintf("UPDATE `admin` SET user_name=%s, password=%s WHERE id=%s",
GetSQLValueString($_POST['user_name'], "text"),
GetSQLValueString($_POST['pass1'], "text"),
GetSQLValueString($_POST['id'], "double"));
mysql_select_db($database_pspm, $pspm);
$Result1 = mysql_query($updateSQL, $pspm) or die(mysql_error());
$updateGoTo = "adminupdate.php";
if (isset($_SERVER['QUERY_STRING'])) {
$updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
$updateGoTo .= $_SERVER['QUERY_STRING'];
}
header(sprintf("Location: %s", $updateGoTo));
}
I try this code before, but not working.
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
Delete this line header(...),replacing it with is code:
echo '<script language="javascript">';
echo 'alert("message successfully sent");';
echo 'window.location="'.$updateGoTo.'";';
echo '</script>';
Please put the javascript code before this code :-
echo '<script>alert("Thanku for submit");</script>';
header(sprintf("Location: %s", $updateGoTo));
Or another method
echo '<script>alert("Thanku for submit");window.location="your path where you want to redirect";</script>';

Javascript/PHP ignore quotes in string

I'm making a music player using php and javascript. I list the files like this:
<?php
if (isset($_GET["action"])) {
$action = htmlspecialchars($_GET["action"]);
if ($action == "listen") {
function listFolderFiles($dir) {
$ffs = scandir($dir);
echo '<ol>';
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
echo '<li>'. $ff . '';
if (is_dir($dir . '/' . $ff)) listFolderFiles($dir . '/' . $ff);
echo '</li>';
}
}
echo '</ol>';
}
listFolderFiles("music");
}
} else {
echo '> listen';
}
?>
And I change the song like this:
<script>
function changesong(url) {
$("#audioplayer").attr("src", url);
$("#audioplayer").trigger('play');
}
</script>
The problem is that songs with quotes in them won't play (for example Don't Stop Me Now). Is there an easy way to fix this?
You should use addslashes(), like this:
echo '<li>'. $ff . '';
You can escape quotes for javascript function in HTML code like this:
Note that you probably need to escape double quotes as well, since they can interfere with HTML tag.
$link = $dir . '/' . $ff;
$link = str_replace("'", "&apos;", $link);
$link = str_replace('"', """, $link);
echo '<li>'. $ff . '';

How to show images onto browser? it's giving me errors

i've successfully uploaded my image into folder and successfully saved my path into database now as i tried to show pic into browser it's showing error:
Warning: mysql_query() expects parameter 2 to be resource, object given in C:\Users\Raj\PhpstormProjects\image\upload_file.php on line 6
Warning: mysql_num_rows() expects parameter 1 to be resource, null given in C:\Users\Raj\PhpstormProjects\image\upload_file.php on line 7
File name not found in database
here is my code for form:
<?php
// Assigning value about your server to variables for database connection
$hostname_connect= "localhost";
$database_connect= "photo";
$username_connect= "root";
$password_connect= "Bhawanku";
$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
#mysql_select_db($database_connect) or die (mysql_error());
if($_POST)
{
// $_FILES["file"]["error"] is HTTP File Upload variables $_FILES["file"] "file" is the name of input field you have in form tag.
if ($_FILES["file"]["error"] > 0)
{
// if there is error in file uploading
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
// check if file already exit in "images" folder.
if (file_exists("images/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{ //move_uploaded_file function will upload your image. if you want to resize image before uploading see this link http://b2atutorials.blogspot.com/2013/06/how-to-upload-and-resize-image-for.html
if(move_uploaded_file($_FILES["file"]["tmp_name"],"images/" . $_FILES["file"]["name"]))
{
// If file has uploaded successfully, store its name in data base
$query_image = "insert into acc_images (image, status, acc_id) values ('".$_FILES['file']['name']."', 'display','')";
if(mysql_query($query_image))
{
echo "Stored in: " . "images/" . $_FILES["file"]["name"];
}
else
{
echo 'File name not stored in database';
}
}
}
}
}
?>
<html>
<body>
<form action="upload_file.php" method="post"enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
and here is my code for showing pics:
<?php
$con=mysqli_connect("localhost","root","Bhawanku","photo");
// Check connection
$query_image = "SELECT * FROM acc_images";
// This query will show you all images if you want to see only one image pass acc_id='$id' e.g. "SELECT * FROM acc_images acc_id='$id'".
$result = mysql_query($query_image, $con);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo '<img alt="" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
?>
In the second script, you're connecting as mysqli but then using mysql_query, mysql_num_rows and mysql_fetch_array. MySQLi and MySQL aren't interchangeable.
$result = mysqli_query($query_image, $con);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
echo '<img alt="" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
You should consider changing the first script to MySQLi too, and use prepared statements instead of concatenating variables into the query.
In first row you use mysqli extension, but in all other - mysql.
Try to change:
<?php
$con=mysql_connect("localhost","root","Bhawanku");
mysql_select_db("photo", $con);
// Check connection
$query_image = "SELECT * FROM acc_images";
// This query will show you all images if you want to see only one image pass acc_id='$id' e.g. "SELECT * FROM acc_images acc_id='$id'".
$result = mysql_query($query_image, $con);
if(mysql_num_rows($result) > 0)
{
while($row = mysql_fetch_array($result))
{
echo '<img alt="" src="images/'.$row["image"].'">';
}
}
else
{
echo 'File name not found in database';
}
?>

Categories