I would like to use the results of a MYSQL query and generate a batch of QR Codes have the following php script via PhpQrCode. What I need is simply display the list of barcodes generated on HTML page. This is what I wrote so far:
<?php
include "qrlib.php";
require "conf/config.php";
$con = mysql_connect(DBSERVER,DBUSER,DBPASS);
mysql_select_db(DBNAME, $con);
$barcodes = mysql_query( "SELECT Description FROM dbo_sensorsandparts ORDER BY ID ASC");
while ($row = mysql_fetch_array($barcodes))
{
echo "<html>";
echo "<img src=";
QRcode::png ($row['Description']);
echo ">";
}
?>
The query is correct since I tested it out but I only get a blank page with a sort of broken image. Can someone help me as to what I am doing wrong please?
Thanks
SOLVED as follows:
<?php
require "conf/config.php";
$con = mysql_connect(DBSERVER,DBUSER,DBPASS);
mysql_select_db(DBNAME, $con);
$barcodes = mysql_query( "SELECT Description FROM dbo_sensorsandparts ORDER BY ID ASC");
//set it to writable location, a place for temp generated PNG files
$PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
//html PNG location prefix
$PNG_WEB_DIR = 'temp/';
include "qrlib.php";
//ofcourse we need rights to create temp dir
if (!file_exists($PNG_TEMP_DIR))
mkdir($PNG_TEMP_DIR);
$filename = $PNG_TEMP_DIR.'label.png';
while ($row = mysql_fetch_array($barcodes))
{
$filename = $PNG_TEMP_DIR.'label'.$row['Description'].'.png';
QRcode::png($row['Description'], $filename);
echo '<img src="'.$PNG_WEB_DIR.basename($filename).'" /><hr/>';
echo $filename;
}
?>
To render the image in the html page, hold the returned QRcode image in a location and then specify it as a link in src attribute of <img> tag.
If QRcode::png returns the raw image data, use data URIs to display:
$qr_code = base64_encode(QRcode::png ($row['Description']));
$src = 'data: image/png;base64,'.$qr_code;
echo '<img src="', $src, '">';
Solved as follows:
<?php
require "conf/config.php";
$con = mysql_connect(DBSERVER,DBUSER,DBPASS);
mysql_select_db(DBNAME, $con);
$barcodes = mysql_query( "SELECT Description FROM dbo_sensorsandparts ORDER BY ID ASC");
//set it to writable location, a place for temp generated PNG files
$PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
//html PNG location prefix
$PNG_WEB_DIR = 'temp/';
include "qrlib.php";
//ofcourse we need rights to create temp dir
if (!file_exists($PNG_TEMP_DIR))
mkdir($PNG_TEMP_DIR);
$filename = $PNG_TEMP_DIR.'label.png';
while ($row = mysql_fetch_array($barcodes))
{
$filename = $PNG_TEMP_DIR.'label'.$row['Description'].'.png';
QRcode::png($row['Description'], $filename);
echo '<img src="'.$PNG_WEB_DIR.basename($filename).'" /><hr/>';
echo $filename;
}
?>
I have stored the PNGs as files via variable $filename.
Related
I want to allow users to upload images without conflicting problems that may be caused by multiple users uploading images that potentially have the same image name. I am stumped on how to execute this and I have no idea where to start..
Here is my code:
if(isset($_POST['submitimage'])){
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$_FILES['file']['name']);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".$_FILES['file']['name']."' WHERE user_id = '".$_SESSION['user']."'");
header("Location: index.php");
}
?>
Any help would be amazing. Thank you!
My solution is to generate a random string for each uploaded file, i.e.:
<?php
if(!empty($_POST['submitimage'])){
//get file extension.
$ext = pathinfo($_FILES['file']['name'])['extension'];
//generate the new random string for filename and append extension.
$nFn = generateRandomString().".$ext";
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$nFn);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '{$nFn}' WHERE user_id = '{$_SESSION['user']}'");
header("Location: index.php");
}
function generateRandomString($length = 10) {
return substr(str_shuffle("abcdefghijklmnopqrstuvwxyz"), 0, $length);
}
?>
PHP has a build in function to generate unique files on your server. This function is known as tempnam(). If you read the comments on that website carefully though, there is a small chance you'll get unwanted behaviour from that function if to many processes call it at the same time. So a modification to this function would be as follows:
<?php
function tempnam_sfx($path, $suffix){
do {
$file = $path."/".mt_rand().$suffix;
$fp = #fopen($file, 'x');
}
while(!$fp);
fclose($fp);
return $file;
}
?>
Because the file is kept open while it's being created, it can't be accessed by another process and therefor it's impossible to ever create 2 files with the same name simply because a couple of your website visitors happened to upload pictures at the exact same moment. So to implement this in your own code:
<?php
function tempnam_sfx($path, $suffix){
do {
$file = $path."/".mt_rand().$suffix;
$fp = #fopen($file, 'x');
}
while(!$fp);
fclose($fp);
return $file;
}
$uploaddir = 'pictures'; // Upload directory
$file = $_FILES['file']['name']; // Original file
$ext = pathinfo($path, PATHINFO_EXTENSION); // Get file extension
$uploadfile = tempnam_sfx($uploaddir, $ext);
move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile);
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".basename($uploadfile)."' WHERE user_id = '{$_SESSION['user']}'");
header("Location: index.php");
?>
One way you could do this, is by generating a few random numbers (and possibly attaching them to current date in number format) and give the image the number sequence.
if(isset($_POST['submitimage'])){
//generate 3 sequences of random numbers,you could do more or less if you wish
$randomNumber=rand().rand().rand();
move_uploaded_file($_FILES['file']['tmp_name'],"pictures/".$randomNumber."jpg");
$con = mysqli_connect("localhost","root","","database");
$q = mysqli_query($con,"UPDATE users SET image = '".$randomNumber.".jpg' WHERE user_id = '".$_SESSION['user']."'");
header("Location: index.php");
}
?>
Note : you could also look into generating random strings if numbers are not your thing.
I am trying to upload Excel file using PHP. I am using WAMP server and written PHP code to upload Excel file in the same folder.
I have saved an Excel file so if I upload the saved file then it works fine but if I try to upload another Excel file from different location i.e. from desktop it is showing that abc.xls is not readable.
My code is as follows:
<?php
ini_set("display_errors",1);
require_once 'excel_reader2.php';
require_once 'db.php';
if(isset($_POST["btnImport"]))
{
if(!empty($_FILES["excelFile"]["tmp_name"]))
{
$fileupload = $_FILES["excelFile"]["name"];
$fileName = explode(".",$_FILES["excelFile"]["name"]);
if($fileName[1]=="xls"||$fileName[1]=="xlsx")
{
$data = new Spreadsheet_Excel_Reader($fileupload);
//echo "Total Sheets in this xls file: ".count($data->sheets)."<br /><br />";
$html="<table border='1'>";
for($i=0;$i<count($data->sheets);$i++) // Loop to get all sheets in a file.
{
if(count(#$data->sheets[$i]['cells'])>0) // checking sheet not empty
{
// echo "Sheet $i:<br /><br />Total rows in sheet $i ".count($data->sheets[$i]['cells'])."<br />";
for($j=1;$j<=count($data->sheets[$i]['cells']);$j++) // loop used to get each row of the sheet
{
$html.="<tr>";
for($k=1;$k<=count($data->sheets[$i]['cells'][$j]);$k++) // This loop is created to get data in a table format.
{
$html.="<td>";
#$html.=$data->sheets[$i]['cells'][$j][$k];
$html.="</td>";
}
#$data->sheets[$i]['cells'][$j][1];
#$ques = mysql_real_escape_string($data->sheets[$i]['cells'][$j][1]);
$opt1 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][2]);
$opt2 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][3]);
$opt3 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][4]);
#$opt4 = mysql_real_escape_string($data->sheets[$i]['cells'][$j][5]);
#$correct = mysql_real_escape_string($data->sheets[$i]['cells'][$j][6]);
#$Level = mysql_real_escape_string($data->sheets[$i]['cells'][$j][7]);
#$Category = mysql_real_escape_string($data->sheets[$i]['cells'][$j][8]);
#$explain = mysql_real_escape_string($data->sheets[$i]['cells'][$j][9]);
$nithi = "INSERT INTO `question` VALUES (NULL,'".$ques."','".$opt1."','".$opt2."','".$opt3."','".$opt4."','".$correct."','".$Level."','".$Category."','".$explain."')";
if (!mysql_query($nithi,$connection))
{
die('Error: ' . mysql_error());
}
$result = mysql_query("SET NAMES utf8");//the main trick
$cmd = "select * from TAMIL";
$result = mysql_query($cmd);
}
}
}}}}
if(#$result){
echo "Questions uploaded successfully";
}
?>
How can I upload Excel file from different location?
When a file is uploaded in PHP, it is put into temp folders.
In your code, there is no call for moving the uploaded file from temporary location into the desired one. Instead you are only checking $_FILES["excelFile"]["tmp_name"] and then directly using $_FILES["excelFile"]["name"] which is obviously incorrect.
Use move_uploaded_file() function to move the file, see the docs: http://php.net/move_uploaded_file
I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress
I'm trying to design a page in php which shows images from database. or I would say only the location of images are in database.
But, when it shows up the images.. But it does print the image path.. That means it is getting the image path without any issue.
Here's my code:
<?php
$con = mysqli_connect("localhost", "root", "", "foodies");
if(mysqli_connect_errno()){
echo "Failed to connect to mysql";
mysqli_connect_error();
}
$sql = "select img, name from products";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$img = $row["img"];
$name = $row["name"];
//$srcc = "C:\wamp\www\foodies\images";
//$quality=100;
//echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
echo "<img src='".$row['img']."' width=200 height=200/>";
?>
I don't think you understand what's going on with the <img> tag. The src attribute needs to be a URL that tells your Web browser how to access the image, not a local file path. (URLs can be made for accessing local files, but that doesn't seem to be what you're doing, and that won't help you make Web-ready software anyway.)
The best way to display images from database is to save the image path in database tables then use Data URLS Schemes.
Try this instead:
<?php $con = mysqli_connect("localhost", "root", "", "foodies");
if(mysqli_connect_errno()){
echo "Failed to connect to mysql";
}
$sql = "select img, name from products";
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$img = $row["img"];
$name = $row["name"];
echo "<img src="data:image/jpeg;base64,<?php echo base64_encode( $img); ?>" width=200 height=200/>";
?>
The $img is the image file name, without the extension. Let's say you have saved your image in a folder "image" and the image file extension is jpeg.
I hope this is helpful.
while($row = mysql_fetch_array($result)) {
if($row['file_location']=="")
{
//your code
}
else
{
?>
VIEW IMAGE
<?php
}
}
Sorry for late reply to this. This was resolved. The issue was that I was giving location starting from root drive and not from root of web folder where the images were actually stored.
Ex: Website and images were located in C:\WAMP\my_site\images\
Instead of giving location from website root folder "\my_site\images\" I was giving it from C:\WAMP.......
Minor mistake though! ;)
Thank you everyone!
I have this database that contains images as strings. Those strings look something like this:
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD...
I need to create a link that will display this image. Like something.com/?id=27 is an image. All the images are in jpeg format. Here's what I've tried but didn't work:
<?php
$host = "smth";
$user = "smth";
$pass = "smth";
$db_name = "smth";
$dbh = new PDO("mysql:host=$host;dbname=$db_name", $user, $pass);
$dbh->exec("SET NAMES utf8");
$q = $dbh->prepare("select content from img where id = :id");
$q->execute(array(':id'=>$_GET['id']));
$row = $q->fetch(PDO::FETCH_BOTH);
header("Content-type: image/jpeg");
echo $row['content'];
?>
The data is being fetched correctly but the image is not displayed.
I need to be able to use this link like this <img src="mysite.com?id=21" /> and I do NOT want this solution: <img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABA..." />
Thanks!
The solution to your problem is here:
How to decode a base64 string (gif) into image in PHP / HTML
Quoting that source but modifying:
In the case you strip out the first case and choose to decode the string, you should add this before echoing the decoded image data:
header("Content-type: image/gif");
$data = "/9j/4AAQSkZJRgABAQEAYABgAAD........";
echo base64_decode($data);
In the second case, use this instead:
echo '<img src="data:image/gif;base64,' . $data . '" />';
The second case is bad because the browser does not perform caching if the same image is shown on multiple pages.
Use this:
$code_base64 = $row['content'];
$code_base64 = str_replace('data:image/jpeg;base64,','',$code_base64);
$code_binary = base64_decode($code_base64);
$image= imagecreatefromstring($code_binary);
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
try this
//your image data
$logodata = "/9j/4AAQSkZJRgABAQEAYABgAAD........";
echo '<img src="data:image/gif;base64,' . $logodata . '" />';
Try this:
echo '<img src="data:image/png;base64,' . $base64encodedString . '" />
/**
* #param $base64_image_content
* #param $path
* #return bool|string
*/
function base64_image_content($base64_image_content,$path){
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
$type = $result[2];
$new_file = $path."/".date('Ymd',time())."/";
$basePutUrl = C('UPLOAD_IMG_BASE64_URL').$new_file;
if(!file_exists($basePutUrl)){
//Check if there is a folder, if not, create it and grant the highest authority.
mkdir($basePutUrl, 0700);
}
$ping_url = genRandomString(8).time().".{$type}";
$ftp_image_upload_url = $new_file.$ping_url;
$local_file_url = $basePutUrl.$ping_url;
if (file_put_contents($local_file_url, base64_decode(str_replace($result[1], '', $base64_image_content)))){
ftp_upload(C('REMOTE_ROOT').$ftp_image_upload_url,$local_file_url);
return $ftp_image_upload_url;
}else{
return false;
}
}else{
return false;
}
}
If you are dealing with data stored in a PostgreSQL database bytea field you will receive a stream when fetching the PDO. To process the data any further first transform the stream to usual data like this: $stream = $row['content']; rewind($stream); $data=stream_get_contents($stream);