To track which person opens my (mailchimp) emails I would like to add a tracking pixel.
The pixel now is generated, but whenever I add GET parameters to the url it won't work
my code for "pixel.php"
<?php
/*
GET Methods
*/
if (!empty($_GET)){
$ip = $_SERVER['REMOTE_ADDR'];
// (Do|log) act on name
if (isset($_GET['name'])) {
$name = $_GET['name'];
} else{
$name = "";
}
// (Do|log) act on mail/campagne id
if (isset($_GET['mailid'])) {
$id = $_GET['mailid'];
}else{
$id = "";
}
// (Do|log) act on date
if (isset($_GET['date'])) {
$date = $_GET['date'];
} else{
$date = "";
}
insert($ip, $name, $mailid, $date);
}else{
// normal browsing to pixel.php without parameters set
// no insert here
}
/*
INSERT
*/
function insert($ip, $name, $mailid, $date){
// Create connection
$conn = mysqli_connect("192.168.****.****", "****", "****", "maildata");
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$query = "INSERT INTO opened (ip, name, mailid, date)
VALUES ('".$ip."', '".$name."', '".$mailid."', '".$date."')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
}
/*
GENERATE IMAGE
*/
// Create an image, 1x1 pixel in size
$im=imagecreate(1,1);
// Set the background colour
$white=imagecolorallocate($im,255,255,255);
// Allocate the background colour
imagesetpixel($im,1,1,$white);
// Set the image type
header("content-type:image/jpg");
// Create a JPEG file from the image
imagejpeg($im);
// Free memory associated with the image
imagedestroy($im);
/*
call with <img src="pixel.php?userid=98798&campaign=302&last=8"> for example
*/
?>
I think the error is somewhere in the INSERT mysql statement but I can't figure out where, and the only feedback I get is an "Image not found"-icon
mysqli_query($conn, $sql);
needs to be
mysqli_query($conn, $query);
Related
I'm trying to insert four images to the database but first image only getting inserted. The first image I could fetch but other images are not returned. But in the table image name are showing.
<?php
header("Location:../index.php");
// Create database connection
$db = mysqli_connect("localhost", "root", "", "alu");
// Initialize message variable
$msg = "";
//If upload button is clicked ...
if (isset($_POST['submit'])) {
//Get image name
$txtproducttitle = $_POST['txtproducttitle'];
$txtProductDescription = $_POST['txtProductDescription'];
$txtProdutPrice = $_POST['txtProdutPrice'];
$AdCondition = $_POST['AdCondition'];
$PrImg1 = $_FILES['PrImg1']['name'];
$PrImg2 = $_FILES['PrImg2']['name'];
$PrImg3 = $_FILES['PrImg3']['name'];
$PrImg4 = $_FILES['PrImg4']['name'];
$AdCategory = $_POST['AdCategory'];
$AdLocation = $_POST['AdLocation'];
$txtname = $_POST['txtname'];
$txtuseremail = $_POST['txtuseremail'];
$txtContact = $_POST['txtContact'];
$AdPayment = $_POST['AdPayment'];
$target = "../upload/".basename($PrImg1);
$sql = "INSERT INTO advertisement (AdTitle, AdDes, AdPrice,
AdCondition, AdImg1, AdImg2, AdImg3, AdImg4, AdCategory, AdLocation,
AdSellName, AdSellMail, AdSellContact, AdPayment)
VALUES ('$txtproducttitle','$txtProductDescription','$txtProdutPrice','$AdCondition','$PrImg1','$PrImg2','$PrImg3','$PrImg4','$AdCategory','$AdLocation','$txtname','$txtuseremail','$txtContact','$AdPayment')";
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['PrImg1']['tmp_name'], $target)) {
$msg = "Ad Successfully Posted";
}else
{
$msg = "Failed To Post Ad";
}
}
$result = mysqli_query($db, "SELECT * FROM advertisement");
You need to use move_uploaded_file function for other images.
Use:
if (move_uploaded_file($_FILES['PrImg2']['tmp_name'], $target2)) {
$msg = "Ad2 Successfully Posted";
}
else
{
$msg = "Failed To Post Ad2";
}
if (move_uploaded_file($_FILES['PrImg3']['tmp_name'], $target2)) {
$msg = "Ad3 Successfully Posted";
}
else
{
$msg = "Failed To Post Ad2";
}
if (move_uploaded_file($_FILES['PrImg4']['tmp_name'], $target2)) {
$msg = "Ad4 Successfully Posted";
}
else
{
$msg = "Failed To Post Ad4";
}
I have used someone else's code that uses the ipaddress way. However, I would like to use a code that checks for the current userid and the id number.
$ipaddress = md5($_SERVER['REMOTE_ADDR']); // here I am taking IP as UniqueID but you can have user_id from Database or SESSION
/* Database connection settings */
$con = mysqli_connect('localhost','root','','database');
if (mysqli_connect_errno()) {
echo "<p>Connection failed:".mysqli_connect_error()."</p>\n";
} /* end of the connection */
if (isset($_POST['rate']) && !empty($_POST['rate'])) {
$rate = mysqli_real_escape_string($con, $_POST['rate']);
// check if user has already rated
$sql = "SELECT `id` FROM `tbl_rating` WHERE `user_id`='" . $ipaddress . "'";
$result = mysqli_query( $con, $sql);
$row = mysqli_fetch_assoc();//$result->fetch_assoc();
if (mysqli_num_rows($result) > 0) {
//$result->num_rows > 0) {
echo $row['id'];
} else {
$sql = "INSERT INTO `tbl_rating` ( `rate`, `user_id`) VALUES ('" . $rate . "', '" . $ipaddress . "'); ";
if (mysqli_query($con, $sql)) {
echo "0";
}
}
}
//$conn->close();
In your database table, set the user_id column as UNIQUE KEY. That way, if a user tries to cast a second vote, then the database will deny the INSERT query and you can just display a message when affected rows = 0.
Alternatively, (and better from a UX perspective) you can preemptively do a SELECT query for the logged in user before loading the page content:
$allow_rating = "false"; // default value
if (!$conn = new mysqli("localhost", "root","","database")) {
echo "Database Connection Error: " , $conn->connect_error; // never show to public
} elseif (!$stmt = $conn->prepare("SELECT rate FROM tbl_rating WHERE user_id=? LIMIT 1")) {
echo "Prepare Syntax Error: " , $conn->error; // never show to public
} else {
if (!$stmt->bind_param("s", $ipaddress) || !$stmt->execute() || !$stmt->store_result()) {
echo "Statement Error: " , $stmt->error; // never show to public
} elseif (!$stmt->num_rows) {
$allow_rating = "true"; // only when everything works and user hasn't voted yet
}
$stmt->close();
}
echo "Rating Permission: $allow_rating";
And if they already have a row in the table, then don't even give them the chance to submit again.
i am using html canvas page for drawing online and i am linking it with save.php file which saves the drawing data from the canvas on my database
and this is the code of save.php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
//echo "ok1";
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$file = ''.rand().'';
$fp = fopen( $file.'.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
//echo "ok2";
$servername = "example";
$username = "example";
$password = "example";
$dbname = "example";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//$usr = wp_get_current_user();
//$uid = (int) $usr->ID;
//echo "ok3";
//global $current_user1;
//$current_user = wp_get_current_user();
//global $current_user;
//get_currentuserinfo();
$root = dirname(dirname(__FILE__));
if (file_exists($root.'/wp-load.php')) {
require_once($root.'/wp-load.php');
//echo "EXISTS";
}
$user_id = get_current_user_id();
//echo "ok4";
$content1 = '<img class="alignnone wp-image-11" src="http://example.com/wp-includes/'.$file.'.png" alt="" />';
// $usr=get_current_user_id();
$sql = "INSERT INTO wp_njvt_posts (post_date,post_date_gmt,post_author, post_content, post_title, post_excerpt, post_password, post_name, to_ping, pinged, post_content_filtered, guid, post_mime_type)
VALUES (NOW(),NOW(),'$user_id','$content1', '', '', '','$file','','','','http://www.example.com/?p=$file','')";
$row_id = 0;
// $usr=0;
if ($conn->query($sql) === TRUE) {
echo "".$file.".png";
$row_id = $conn->insert_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$sql2 = "UPDATE wp_njvt_posts SET guid = 'http://www.example.com/?p=$row_id' WHERE ID = $row_id" ;
if ($conn->query($sql2) === TRUE) {
echo " ***your drawing was published SUCCESSFULY!*** ";
//header("Location: http://www.example.com/?p=$row_id");
} else {
echo "Error:". $sql2 . "<br>" . $conn->error;
}
$conn->close();
}
now the drawing gets a link like http://www.example.com/?p=$row_id and i tried redirect the user after publishing the drawing to that link and i tried it with
header("Location: http://www.example.com/?p=$row_id");
but it is not working with me!
any other solutions other than (header) ?
I am facing an issue to get images from database. I went through so many articles of stack and other websites also, but none have the solution I am looking for. How can I get images stored in the database on the page?
Here is the code, kindly check it and let me know what mistake I made. All help is really appreciated.
<?php
// I have database name databaseimage
// I have a table named store
// I have 3 columns into the table store
// id (int primary key ai), name (varchar), and image (longblob)
// prevent accesing the page directly
if($_SERVER['REQUEST_METHOD'] !='POST') {
echo "you can not acces this page directly";
die();
}
else {
print_r($_FILES);
// file properties
$file = $_FILES['image']['tmp_name'];
echo "<br>$file";
if(!isset($file)){
echo "please select an image";
die();
} else {
//actual image
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])) ;
// image name
$image_name = addslashes($_FILES['image']['name']);
echo "<br> image name is = $image_name";
//geting image size to check whether it is actually an image or not
$image_size = getimagesize($_FILES['image']['tmp_name']);
echo "<br>";
print_r($image_size);
if($image_size==FALSE) {
echo "plese select an images only";
die();
}
else {
#code to put an image into the database
// connect to database
try {
$con = new PDO("mysql:host=localhost;dbname=databaseimage", "root",
"");
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "<br>connection succesfull";
// make a query
$extr = $con->prepare("INSERT INTO store (name, image)
VALUES (:na , :im)" );
//$a=1;
//$extr->bindParam(':i', $a);
$extr->bindParam(':na', $image_name);
$extr->bindParam(':im', $image, PDO::PARAM_LOB);
if ( $extr->execute()==true) {
echo "<br>image uploaded succesfully";
# insert is working. I can insert images into database
# but really facing problem while displaying those images
# below is the code I tried
# CODE for to show uploaded files
# to show images which is uploaded
$show = $con->prepare("SELECT * FROM store ");
//$a = 1;
//$show->bindParam(':iam', $a);
$show->execute();
while ($row = $show->fetch(PDO::FETCH_BOUND) ) {
# SHOW IMAGES
//echo "<img src = '$row[image]' alt='image' >";
echo '<img src= "data:image/png;base64,'.base64_encode($row['image']).'"
height="100" width="100" />';
}
} else {
echo "<br>image not uploaded";
}
}
catch(Exception $e)
{
echo "<br> Connection failed: " . $e->getMessage();
}
}
}
// disconnect the connection
$con = null;
}
?>
Step 1: create a php script with filename getimage.php with the
following code:
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$con = new PDO("mysql:host=localhost;dbname=databaseimage", "root",
"");
$sql = "SELECT image FROM store WHERE id=$id";
$stmt=$con->query($sql);
$res=$stmt->fetch(PDO::FETCH_ASSOC);
$con=null;
header("Content-type: image/pn")g;
echo $res['image'];
?>
Step 2: In your current php page (below the comment "# below is the code i tried") try the following code:
$show = $con->prepare("SELECT id FROM store ");
//$a = 1;
//$show->bindParam(':iam', $a);
$show->execute();
while ($row = $show->fetch(PDO::FETCH_NUM) ) {
# SHOW IMAGES
echo '<img src="getimage.php?id="'.$row[0].'"
height="100" width="100" />';
}
im having a problem with my code in uploading and displaying images.. well I am planning to redirect the page after the upload process is done so I used a header function but gave warning and errors and unfortunately failed the upload.. how can I remove it? here's the code..
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel)
{
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION";
}
//file properties//
$file = $_FILES['image']['tmp_name'];
echo '<br />';
/*if(!isset($file))
echo "Please select your images";
else
{
*/for($count = 0; $count < count($_FILES['image']); $count++)
{
//$image = file_get_contents($_FILES['image']['tmp_name']);
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]); echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results)
echo "Problem uploding the image. Please check your database";
//else
//{
echo "";
//$last_id = mysql_insert_id();
//echo "Image Uploaded. <p /> <p /><img src=display.php? id=$last_id>";
//header('Lcation: display2.php?id=$last_id');
}
//}
}
mysql_close($con);
header('Location: fGallery.php');
?>
the header function supposedly directs me to another page that would make a gallery.. here is the code..
<?php
//connect to the database//
mysql_connect("localhost","root", "") or die(mysql_error());
mysql_select_db("imagedatabase") or die(mysql_error());
//requesting image id
$image = mysql_query("SELECT * FROM images ORDER BY id DESC");
while($row = mysql_fetch_assoc($image))
{
foreach ($row as $img) echo '<img src="img.php?id='.$img["id"].'">';
}
mysql_close();
?>
I have also a problem with my gallery .. some help will be GREAT! THANKS! :D
The header() function must be called before any other echo or die calls which produce output.
You may could buffer your outputs if you need the output, but in your case it makes no difference because the output will never be shown to the user. The browser will read the redirect and navigate to the second page.
<?php
//connect to the database//
$con = mysql_connect("localhost","root", "");
if(!$con) {
// this output is okay the redirect will never be reached.
die('Could not connect to the database:' . mysql_error());
// remember after a die this message will never be shown!
echo "ERROR IN CONNECTION";
}
$sel = mysql_select_db("imagedatabase");
if(!$sel) {
die('Could not connect to the database:' . mysql_error());
echo "ERROR IN CONNECTION"; // same here with the die!
}
//file properties//
$file = $_FILES['image']['tmp_name'];
// OUTPUT
// echo '<br />';
// removed out commented code
for($count = 0; $count < count($_FILES['image']); $count++)
{
$image_desc[$count] = addslashes($_POST['imageDescription'][$count]);
$image_name[$count] = addslashes($_FILES['image]']['name'][$count]);
// OUTPUT
// echo '<br \>';
$image_size[$count] = #getimagesize($_FILES['image']['tmp_name'][$count]);
$error[$count] = $_FILES['image']['error'][$count];
if($image_size[$count] === FALSE || ($image_size[$count]) == 0)
// you may better use a die if you want to prevent the redirection
echo "That's not an image";
else
{
// Temporary file name stored on the server
$tmpName[$count] = $_FILES['image']['tmp_name'][$count];
// Read the file
$fp[$count] = fopen($tmpName[$count], 'r');
$data[$count] = fread($fp[$count], filesize($tmpName[$count]));
$data[$count] = addslashes($data[$count]);
fclose($fp[$count]);
// Create the query and insert
// into our database.
$results = mysql_query("INSERT INTO images( description, image) VALUES ('$image_desc[$count]','$data[$count]')", $con);
if(!$results) // use die
echo "Problem uploding the image. Please check your database";
// OUTPUT
// echo "";
}
}
mysql_close($con);
header('Location: fGallery.php');
?>
Above I marked every output for you and also removed all outcomments lines.
You've got a header error because you printed out <br /> before the header function. In order to use the header function you can't print out any information before it. That's why you're getting the error.
Regarding your gallery the foreach loop is unnecessary. You can change the code to this:
while($row = mysql_fetch_assoc($image)) {
echo '<img src="img.php?id='.$row["id"].'">';
}
You can use ob_start() to get data in buffer.