php page redirection to another page - php

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) ?

Related

PHP echo images that stored outside of "public_html" in specific div

To print image in certain div, basically what I'm doing it's: echo first part of html page before that "div" (myGallery.html)/ then php script -> echo images from secure folder outside of public_html/ then second part of html (myGallery1.html) after specific "div".
Please give me some basic idea how to do it in normal way.
<?php
$userMail = $_POST["email"] = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$password = $_POST["pass"] = filter_var($_POST['password'], FILTER_SANITIZE_STRING);
$userMail = strtolower("$userMail");
$userMail = stripcslashes($userMail);
$password = stripcslashes($password);
$database = file_get_contents( "/home/customer/www/domain/System/sysData.json");
$obj = json_decode($database);
$dbusername = $obj->username;
$dbpassword = $obj->password;
$my_db = $obj->my_db;
$conn = new mysqli("localhost", $dbusername, $dbpassword, $my_db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, username, email, password FROM customers";
$result = $conn->query($sql);
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
if ($row["email"] == $userMail && $row["password"] == $password) {
echo "Login Succes". "<br>";
$gal = file_get_contents( "/home/customer/www/domain/public_html/Log/myGallery.html");
echo $gal;
$dir = "/home/customer/www/domain/myGallery";
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if ($file == '.' or $file == '..') continue;
$path = '/home/customer/www/domain/myGallery/'. $file;
$imgData = base64_encode(file_get_contents($path));
$src = 'data: '.mime_content_type($path).';base64,'.$imgData;
echo "<img class=\"images\" src=\"$src\" data=\"$file\" >";
}
closedir($dh);
}
};
$gal1 = file_get_contents( "/home/customer/www/domain/public_html/Log/myGallery1.html");
echo $gal1;
} else {
echo "Failed to LogIn";
};
$conn->close();
?>
Like a simple templating system you need a way to determine where content should be placed. For something this simple, in myGallery.html just add a comment <!-- IMAGES --> or something that is unique like {{IMAGES}} or whatever as a marker:
<html>
<head>
</head>
<body>
<div>
<!-- IMAGES -->
</div>
</body>
</html>
Then you can do one of several things. You can split the file contents and echo when needed:
$gal = file_get_contents("/home/customer/www/domain/public_html/Log/myGallery.html");
$parts = explode('<!-- IMAGES -->', $gal);
echo $parts[0];
// loop and get image content
// echo image content
// end loop
echo $parts[1];
Or modify your loop to store and not display the images, then replace the marker with the image tags:
// loop and get image content
$images[] = "<img class=\"images\" src=\"$src\" data=\"$file\" >";
// end loop
$gal = file_get_contents("/home/customer/www/domain/public_html/Log/myGallery.html");
echo str_replace('<!-- IMAGES -->', implode($images), $gal);

android uploading empty image to the host using php

I'm trying to upload a photo from an android device to host using PHP and base 64, bitmap ; but it uploads two empty images (it uploads two times) can't figure out why, any help or alternative way?
I'm uploading the photo in a register layout so I tried just inserting the photo without anything else, and I tried using another hosting service but unfortunately, nothing worked.
the name of the empty photo is inserted in the database yet in the file manager it's an empty photo
the php code;
<?php
// array for JSON response
$response = array();
$user_image= $_POST['user_image'];
$user_name= $_POST['user_name'];
$user_email= $_POST['user_email'];
$user_un= $_POST['user_un'];
$user_pass= $_POST['user_pass'];
$servername = "...";
$username = "...";
$password = "...";
$dbname = "...";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset("utf8");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}else{
$ra=rand(0,20000);
$rn=rand(0,40000);
$rd=rand(0,60000);
$imgname = "pl".$ra.$rn.$rd.".jpeg";
$decoding=base64_decode("$user_image");
file_put_contents("images/".$imgname,$decoding);
$sql = "INSERT INTO Users (user_name,user_email,user_un,user_pass,user_image)
VALUES ('$user_name','$user_email','$user_un','$user_pass','$imgname')";
if ($conn->query($sql) === TRUE) {
$UserId = $conn->insert_id;
$response['dishs'] = array();
$hobbie['status'] = "ok";
$hobbie['result'] = "Welcome";
// push single dishinto final response array
array_push($response['dishs'],$hobbie);
// echoing JSON response
echo json_encode($response);
} else {
// echo "Error: " . $sql . "" . $conn->error;
$response['dishs'] = array();
// failed to insert row
$hobbie['status'] = "no";
$hobbie['result'] = "Error: " . $sql . "" . $conn->error;
array_push($response['dishs'],$hobbie);
// echo no users JSON
echo json_encode($response);
}
}
$conn->close();
?>
the kotlin code
these are defined in the head of the class
"class RegisterPage :Fragment() {
var encodImg = ""
var bitmap: Bitmap? = null
......
"
sending this to the host
"... val params = HashMap<String, String>()
params["user_image"] = encodImg
...
"
the way i choose the photo from gallery and encrypt
private fun startGallery() {
val galleryIntent = Intent(Intent.ACTION_GET_CONTENT)
galleryIntent.type = "image/*"
if (galleryIntent.resolveActivity(activity!!.packageManager) != null) {
startActivityForResult(galleryIntent, 1000)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, i: Intent?) {
super.onActivityResult(requestCode, resultCode, i)
if (resultCode == Activity.RESULT_OK) {
val uri: Uri? = i!!.data
change_profile_photo.setImageURI(uri)
manageImageFromUri(i.data!!)
} else {
Toast.makeText(activity, "Error", Toast.LENGTH_LONG).show()
}
}
private fun manageImageFromUri(imageUri: Uri) {
val baos = ByteArrayOutputStream()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
Snackbar.make(view!!, "ERROR", Snackbar.LENGTH_LONG)
} else {
bitmap = MediaStore.Images.Media.getBitmap(activity?.contentResolver, imageUri)
bitmap!!.compress(Bitmap.CompressFormat.JPEG, 100, baos)
val b = baos.toByteArray()
encodImg = Base64.encodeToString(b, Base64.DEFAULT)
}
}
}

PHP tracking pixel database insert

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);

I have used a foreach to compare two strings based on the username i just eliminate the targeted file address form the filename

I have used a foreach to compare two strings based on the username, then I just eliminate the targeted file address from the filename and store it in the database.
When I enter the actual filename manually I can get the output.
But when I try to run in foreach, the filename remains unaffected by the code.
Please some one help... I have bolded the code that has problem...
<?php
$directory = "shared/*/";
//get all image files with a .jpg extension.
$images = glob("" . $directory . "*.jpg");
$imgs = '';
// create array
foreach($images as $image) {
$imgs[] = "$image";
}
//shuffle array
shuffle($imgs);
//select first 20 images in randomized array
$imgs = array_slice($imgs, 0, 20);
//display images
foreach ($imgs as $img) {
echo "<img width='320pts' hight='240pts' src='$img' /> ";
echo '<form method="post" >';
echo '<input type="hidden" value="'.$img.'" name="cmt" />';
echo '<input type="text" name="txt" />';
echo "<input type='submit' value='comment' />";
echo '</form>';
}
?>
<?php
global $viky;
$dbhost = 'localhost';
$dbuser = 'viky';
$dbpass = 'password';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT username FROM register";
mysql_select_db('login');
$retval = mysql_query( $sql, $conn );
if (!$retval) {
die('Could not get data: ' . mysql_error());
}
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
$all[] = $row['username'];
}
foreach ($all as $alls) {
$viky[] = $alls;
}
if (array_key_exists('cmt', $_POST)) {
$filename = $_POST['cmt'];
if (file_exists($filename)) {
global $d;
$d=$_POST['txt'];
echo "{$_POST['txt']}";
{
{
foreach($viky as $vig)
{
$str="{$filename}";
$str2="shared/{$vig}/";
echo $str2."<br>".$str."<br>";
file_put_contents("tt.txt", "");
$a=fopen('tt.txt','w');
fwrite($a,$str );
$haystack = file('tt.txt'); /* put contents into an array */
$needle1 = "shared/{$vig}/"; /* value to be replaced */
$needle2 =""; /* value doing the replacing */
for($i=0;$i<count($haystack);$i++) {
$haystack[$i] = str_ireplace($needle1, $needle2, $haystack[$i]); /* case insensitive replacement */
}
$content = implode("\n", $haystack); /* put array into one variable with newline as delimiter */
file_put_contents('tt.txt', $content); /* over write original with changes made */
$needle1 = " "; /* value to be replaced */
$needle2 ="_"; /* value doing the replacing */
for($i=0;$i<count($haystack);$i++) {
$haystack[$i] = str_ireplace($needle1, $needle2, $haystack[$i]); /* case insensitive replacement */
}
$content = implode("\n", $haystack); /* put array into one variable with newline as delimiter */
file_put_contents('tt.txt', $content); /* over write original with changes made */
$needle1 = ".jpg"; /* value to be replaced */
$needle2 =""; /* value doing the replacing */
for($i=0;$i<count($haystack);$i++) {
$haystack[$i] = str_ireplace($needle1, $needle2, $haystack[$i]); /* case insensitive replacement */
}
$content = implode("\n", $haystack); /* put array into one variable with newline as delimiter */
file_put_contents('tt.txt', $content); /* over write original with changes made */
$c=file_get_contents("tt.txt");
echo $c;
}}
?>**
<?php
$dbhost = 'localhost';
$dbuser = 'viky';
$dbpass = 'password';
$db='comment';
$table=$c;
$con=mysqli_connect($dbhost,$dbuser,$dbpass,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Create table
$sql = "CREATE TABLE {$table}
(
PID INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(PID),
username CHAR(15),
comment CHAR(15)
)";
// Execute query
if (mysqli_query($con,$sql))
{
echo "Table persons created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($con);
}
mysqli_close($con);
?>
<?php
$con=mysqli_connect($dbhost,$dbuser,$dbpass,$db);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO {$table} (username, comment)
VALUES ('{$c}', '{$d}')");
mysqli_close($con);
?>
<?php
}
}
else {
echo 'Could not delete '.$filename.', file does not exist';
}
}
?>
It is hard to find the thing in your code, but what I can say:
You must use reference to be able to edit current element in array using foreach.
Like
$names = array("A", "B") ;
foreach($names as &$name){ //Note sign & means reference
$name = "AnotherName" ;
}

how to remove the header error

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.

Categories