• 0

[PHP][MySQL] compare session info to db in a query


Question

Hi,

I got a log-in script going and I have it so it sets up a new session() when it logs the user in.

i have on my index.php a session_start() that stores $_SESSION['user_id'] = $row['user_id']; and $_SESSION['username'] = $row['username'].

then in my account.php I thought of doing the samething and add to my session more information so I did another db query and tried to created my $_SESSION variables to store the extra info I wanted to pull out.

My syntax is correct, and my SQL query is correct aswell.

include 'dbc.php';
page_protect();
session_start(); 	

$row = mysql_fetch_assoc(mysql_query("SELECT company_name FROM agent_company WHERE agent_id = '{$_SESSION['user_id']}'"));

		if($row['company_name'])
		{
			$_SESSION['company_name'] = $row['company_name'];

			exit;
		}

as you can see I'm trying to pull the data by comparing that it will only pull that data that belongs to the user of the current session. I used my $_SESSION['user_id'] that was created in my index.php here.

Can I not pull session data on a new page with an existing session? or do I need to add ALL the information I want to use all in one swoop? then just access it later on when I need it...?

in my page_protect() function I have this

function page_protect() {
session_start();

//check for cookies

if(isset($_COOKIE['user_id']) && isset($_COOKIE['username'])){
 	$_SESSION['user_id'] = $_COOKIE['user_id'];
 	$_SESSION['username'] = $_COOKIE['username'];
 }


if (!isset($_SESSION['user_id']))
{
header("Location: account.php");
}

Recommended Posts

  • 0

Yes, it's perfectly fine to add new data to $_SESSION. I presume that this is not working for you however...

Firstly, session_start() is being called twice, so correct that.

You mentioned that your login code sets up a new session; How are you doing this, are you sure you're not destroying the user_id and username session data?

You say that your SQL query is correct, but you've got quotes around {$_SESSION['user_id']}; Isn't the user_id a number? If so, then you shouldn't have the quotes! Also, the query would be much better with a LIMIT 1.

This code

$row = mysql_fetch_assoc(mysql_query("SELECT company_name FROM agent_company WHERE agent_id = '{$_SESSION['user_id']}'"));
if($row['company_name'])
{

is much better as follows

$res = mysql_query("SELECT company_name FROM agent_company WHERE agent_id={$_SESSION['user_id']} LIMIT 1");
if (!$res) { die('Error: ' . mysql_error()); }
if (mysql_num_rows($res) == 1)
{
        $row = mysql_fetch_assoc($res);

or if you'd rather not use mysql_num_rows() because you feel it's unnecessary, at least do

if (isset($row['company_name']))

Now, if none of the above has helped uncover the problem, we can do some trouble shooting:

1) change

$res = mysql_query("SELECT company_name FROM agent_company WHERE agent_id={$_SESSION['user_id']} LIMIT 1");

temporarily to

$sql = "SELECT company_name FROM agent_company WHERE agent_id={$_SESSION['user_id']} LIMIT 1";
echo 'sql: ' . $sql;
$res = mysql_query($sql);

and check it's as it should be

2) try var_dump($_SESSION) in various places to check what's in $_SESSION (note, sometimes easiest to view the output of it in the html source code via your browser!

  • 0

hmmm, I found my problem.

I had an exit; in my IF statement... i don't why I had that in there.... its not good to be up in the wee hours of the morning doing php... *sigh*

thx for your help tho, I didn't realize I had those quotes in my user_id in my sql statement!

  • 0

Looks fine, that is apart from the fact that you're half trying to construct a string, and half trying to run a query in what you posted ;)

Btw, using the "or die()" method is often fine when trying to establish a database connection, however, when running queries you might want to use a cleaner method, e.g.

$sql = "INSERT INTO agent_settings (bannerORIGINAL, bannerTHUMB) VALUES ('$consname', '$consname2') WHERE agent_id = {$_SESSION['user_id']}";
$res = mysql_query($sql);
if (!$res) {
        echo "<b>Error: Problem occurred with Database Query!</b><br /><br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "\n";
} else {
        //continue
}

or, using a variable like $errorOccured could result in less nested if statements

$errorOccured = false;

$sql = "INSERT INTO agent_settings (bannerORIGINAL, bannerTHUMB) VALUES ('$consname', '$consname2') WHERE agent_id = {$_SESSION['user_id']}";
$res = mysql_query($sql);
if (!$res) {
        $errorOccured = true;
        echo "<b>Error: Problem occurred with Database Query!</b><br /><br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "\n";
}

if (!$errorOccured) {
        //do more stuff
}

or, functions can also help tidy code up by allowing you to jump out of them when an error has occurred

function myFunction()
{
        $sql = "INSERT INTO agent_settings (bannerORIGINAL, bannerTHUMB) VALUES ('$consname', '$consname2') WHERE agent_id = {$_SESSION['user_id']}";
        $res = mysql_query($sql);
        if (!$res) {
                echo "<b>Error: Problem occurred with Database Query!</b><br /><br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "\n";
                return false;
        }

        //do more stuff

        return true;
}

  • 0

Looks fine, that is apart from the fact that you're half trying to construct a string, and half trying to run a query in what you posted wink.gif

Btw, using the "or die()" method is often fine when trying to establish a database connection, however, when running queries you might want to use a cleaner method, e.g.

$sql = "INSERT INTO agent_settings (bannerORIGINAL, bannerTHUMB) VALUES ('$consname', '$consname2') WHERE agent_id = {$_SESSION['user_id']}";
$res = mysql_query($sql);
if (!$res) {
        echo "<b>Error: Problem occurred with Database Query!</b><br /><br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "\n";
} else {
        //continue
}

or, using a variable like $errorOccured could result in less nested if statements

$errorOccured = false;

$sql = "INSERT INTO agent_settings (bannerORIGINAL, bannerTHUMB) VALUES ('$consname', '$consname2') WHERE agent_id = {$_SESSION['user_id']}";
$res = mysql_query($sql);
if (!$res) {
        $errorOccured = true;
        echo "<b>Error: Problem occurred with Database Query!</b><br /><br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "\n";
}

if (!$errorOccured) {
        //do more stuff
}

or, functions can also help tidy code up by allowing you to jump out of them when an error has occurred

function myFunction()
{
        $sql = "INSERT INTO agent_settings (bannerORIGINAL, bannerTHUMB) VALUES ('$consname', '$consname2') WHERE agent_id = {$_SESSION['user_id']}";
        $res = mysql_query($sql);
        if (!$res) {
                echo "<b>Error: Problem occurred with Database Query!</b><br /><br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "\n";
                return false;
        }

        //do more stuff

        return true;
}

Well I see your point ;)

this is the block of code I have where I took my snippet from.

   $consname = "uploads/" . $username . "/images/banner/" . $image_name;
   //location to where the thumbnail image will be uploaded to
   $consname2 = "uploads/" . $username . "/images/banner/thumbs/" . $image_name;
   $copied = copy($_FILES['cons_image']['tmp_name'], $consname);
   $copied = copy($_FILES['cons_image']['tmp_name'], $consname2);
   $sql = "INSERT INTO agent_settings (bannerORIGINAL, bannerTHUMB) VALUES ('$consname', '$consname2') WHERE agent_id = {$_SESSION['user_id']}" or die(mysql_error());
   $query = mysql_query($sql)or die(mysql_error());
   //$sql="UPDATE agent_settings SET bannerORIGINAL= '$consname' WHERE agent_id={$_SESSION['user_id']}" or die(mysql_error()); //$query = mysql_query($sql)or die(mysql_error());
   //$sql="UPDATE agent_settings SET bannerTHUMB= '$consname2' WHERE agent_id= {$_SESSION['user_id']}" or die(mysql_error());
   //$query = mysql_query($sql)or die(mysql_error());
   //we verify if the image has been uploaded, and print error instead
   if (!$copied) {
    echo 'Copy unsuccessfull!';
    $errors = 1;
   }else{
    // the new thumbnail image will be placed in images/thumbs/ folder
    $thumb_name = $consname2 ;
    // call the function that will create the thumbnail. The function will get as parameters
    //the image name, the thumbnail name and the width and height desired for the thumbnail
    $thumb = make_thumb($consname, $thumb_name, WIDTH, HEIGHT);
    $thumb = make_thumb($consname, $consname, WIDTH2, HEIGHT2);
   }

  • 0

Here is my entire script, maybe you can see what I'm doing wrong ={

dbc.php = my database connection function

sessions.php = where I pull all the data I need from the database and append it to a session variable

page_protect() = a function in my dbc.php that checks to see if the page is being accessed without first login in, if not then it fill redirect you to my index.php

upload.php

set_time_limit(0);
include 'dbc.php';
include 'sessions.php';
page_protect();

//define a maxim size for the uploaded images
define ("MAX_SIZE", "500");
// define the width and height for the thumbnail
// note that theese dimmensions are considered the maximum dimmension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH", "150"); //set here the width you want your thumbnail to be
define ("HEIGHT", "150"); //set here the height you want your thumbnail to be.
define ("WIDTH2", "299"); //set here the width you want your thumbnail to be
define ("HEIGHT2", "299"); //set here the height you want your thumbnail to be.
// this is the function that will create the thumbnail image from the uploaded image
// the resize will be done considering the width and
//height defined, but without deforming the image
function make_thumb($img_name, $filename, $new_w, $new_h){
	//get image extension.
	$ext = getExtension($img_name);
	//creates the new image using the appropriate function from gd library
	if(!strcmp("jpg", $ext) || !strcmp("jpeg", $ext))
		$src_img = imagecreatefromjpeg($img_name);
	if(!strcmp("png", $ext))
		$src_img = imagecreatefrompng($img_name);
	if(!strcmp("gif", $ext))
		$src_img = imagecreatefromgif($img_name);
	//gets the dimmensions of the image
	$old_x = imageSX($src_img);
	$old_y = imageSY($src_img);
	// next we will calculate the new dimmensions for the thumbnail image
	// the next steps will be taken:
	// 1. calculate the ratio by dividing the old dimmensions with the new ones
	// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
	// and the height will be calculated so the image ratio will not change
	// 3. otherwise we will use the height ratio for the image
	// as a result, only one of the dimmensions will be from the fixed ones
	$ratio1 = $old_x / $new_w;
	$ratio2 = $old_y / $new_h;
	if($ratio1 > $ratio2) {
		$thumb_w = $new_w;
		$thumb_h = $old_y / $ratio1;
	}else{
		$thumb_h = $new_h;
		$thumb_w = $old_x / $ratio2;
	}
	// we create a new image with the new dimmensions
	$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
	// resize the big image to the new created one
	imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
	// output the created image to the file. Now we will have the thumbnail into the file named by $filename
	if(!strcmp("png", $ext))
		imagepng($dst_img,$filename);
	else
		imagejpeg($dst_img,$filename);
	if (!strcmp("gif", $ext))
		imagegif($dst_img,$filename);
	//destroys source and destination images.
	imagedestroy($dst_img);
	imagedestroy($src_img);
}
// This function reads the extension of the file.
// It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
	$i = strrpos($str, ".");
	if (!$i) { return ""; }
	$l = strlen($str) - $i;
	$ext = substr($str, $i + 1, $l);
	return $ext;
}
// This variable is used as a flag. The value is initialized with 0 (meaning no error found)
// and it will be changed to 1 if an error occures. If the error occures the file will not be uploaded.
$errors = 0;
// checks if the form has been submitted
if(isset($_POST['Submit'])) {
	//reads the name of the file the user submitted for uploading
	$image=$_FILES['cons_image']['name'];
	// if it is not empty
	if ($image) {
		// get the original name of the file from the clients machine
		$filename = stripslashes($_FILES['cons_image']['name']);
		// get the extension of the file in a lower case format
		$extension = getExtension($filename);
		$extension = strtolower($extension);
		// if it is not a known extension, we will suppose it is an error, print an error message
		// and will not upload the file, otherwise we continue
		if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
			echo 'Unknown extension! Please use .gif, .jpg or .png files only.';
			$errors = 1;
		}else{
			// get the size of the image in bytes
			// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which
			//the uploaded file was stored on the server
			$size = getimagesize($_FILES['cons_image']['tmp_name']);
			$sizekb = filesize($_FILES['cons_image']['tmp_name']);
			//compare the size with the maxim size we defined and print error if bigger
			if ($sizekb > MAX_SIZE*1024) {
				echo 'You have exceeded the 1MB size limit!';
				$errors = 1;
			}
			$rand = rand(0, 1000);
			//we will give an unique name, for example a random number
			$image_name = $rand . '.' . $extension;
			//the new name will be containing the full path where it will be stored (images folder)
			//location to where the original image will be uploaded to
			$consname = "uploads/" . $username . "/images/banner/" . $image_name;
			//location to where the thumbnail image will be uploaded to
			$consname2 = "uploads/" . $username . "/images/banner/thumbs/" . $image_name;
			$copied = copy($_FILES['cons_image']['tmp_name'], $consname);
			$copied = copy($_FILES['cons_image']['tmp_name'], $consname2);
			$query = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE `bannerORIGINAL` AND `bannerTHUMB` NOT NULL";
			$result = mysql_query($result);
			if(!$result) {
				echo "<b>Error: Problem occurred with Database Query!</b><br /><br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "\n";
				$sql = "INSERT INTO agent_settings (bannerORIGINAL, bannerTHUMB) VALUES ('$consname', '$consname2') WHERE agent_id = {$_SESSION['user_id']}";
				exit(); // delete if causing problems
			}else{
				$sql="UPDATE `agent_settings` SET `bannerORIGINAL` = '$consname' WHERE `agent_id` = {$_SESSION['user_id']}" or die(mysql_error());
				$query = mysql_query($sql)or die(mysql_error());
				$sql="UPDATE `agent_settings` SET `bannerTHUMB` = '$consname2' WHERE `agent_id` = {$_SESSION['user_id']}" or die(mysql_error());
				$query = mysql_query($sql)or die(mysql_error());

				//we verify if the image has been uploaded, and print error instead
				if (!$copied) {
					echo 'Copy unsuccessfull!';
					$errors = 1;
				}else{
					// the new thumbnail image will be placed in images/thumbs/ folder
					$thumb_name = $consname2 ;
					// call the function that will create the thumbnail. The function will get as parameters
					//the image name, the thumbnail name and the width and height desired for the thumbnail
					$thumb = make_thumb($consname, $thumb_name, WIDTH, HEIGHT);
					$thumb = make_thumb($consname, $consname, WIDTH2, HEIGHT2);
				}
			}
		}
	}
}
//If no errors registred, print the success message and how the thumbnail image created
if(isset($_POST['Submit']) && !$errors) {
	echo "Thumbnail created Successfully!";
	echo '< img src="'.$thumb_name.'">';
	echo $lastid;
}
?>
<form name="newad" method="post" enctype="multipart/form-data" action="">
<input type="file" name="cons_image" />
<input name="Submit" type="submit" id="image1" value="Upload image" />
</form>

  • 0

well, quite a bit actually :(

$result = mysql_query($result);

should be

$result = mysql_query($sql);

this:

$query = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE `bannerORIGINAL` AND `bannerTHUMB` NOT NULL";

is invalid SQL, it should be

$query = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE `bannerORIGINAL` NOT NULL AND `bannerTHUMB` NOT NULL";

what on earth is this line doing?:

$sql = "INSERT INTO agent_settings (bannerORIGINAL, bannerTHUMB) VALUES ('$consname', '$consname2') WHERE agent_id = {$_SESSION['user_id']}";

it's just sitting there in the middle of your error code and serves absolutely no purpose!

this query (mentioned above)

$query = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE `bannerORIGINAL` AND `bannerTHUMB` NOT NULL";

seems to actually be serving no purpose at all... what are you doing with the data returned, I don't see anything...

then this

$sql="UPDATE `agent_settings` SET `bannerORIGINAL` = '$consname' WHERE `agent_id` = {$_SESSION['user_id']}" or die(mysql_error());
$query = mysql_query($sql)or die(mysql_error());
$sql="UPDATE `agent_settings` SET `bannerTHUMB` = '$consname2' WHERE `agent_id` = {$_SESSION['user_id']}" or die(mysql_error());
$query = mysql_query($sql)or die(mysql_error());

firstly the query can be combined into one!

$sql = "UPDATE `agent_settings` SET `bannerORIGINAL`='$consname', `bannerTHUMB`='$consname2' WHERE `agent_id`={$_SESSION['user_id']};";

but also, this code has not been corrected following previous advise of mine!

And that's possibly just the start... :/

  • 0

*cries*

I'm just beginning my PHP and SQL havoc ;)

I'm not very good yet, but I'm starting to get the logic somewhat.

Ok let me see if I can explain my ideas here...

*ahem*

after the image manipulation and handling I was trying to add it to my database.

If the use has null in both fields bannerORIGINAL and bannerTHUMB then it will insert the url data into those fields, if it isn't null then it will update the fields.... pretty much in a nut shell...

  • 0

If a *record* that you want to modify does not exist, then you insert it, otherwise you update it. Whether or not a field is null, you just update the contents, nothing more to it... However there is a valid reason for a check here - if they are not null then it means there's an existing image that your going to want to delete after you replace it i expect...

  • 0

yep, thats what I was trying to do.

if its already there meaning that the user had previously uploaded an image then just update the record to the new image the user wants to upload again.

but other than that, is my logic for my code right?... atleast? where is it that i'm going wrong in having these records created/updated?

  • 0

I changed it to this... maybe it makes more sense now! ;)

			$consname = "uploads/" . $username . "/images/banner/" . $image_name;
			//location to where the thumbnail image will be uploaded to
			$consname2 = "uploads/" . $username . "/images/banner/thumbs/" . $image_name;
			$copied = copy($_FILES['cons_image']['tmp_name'], $consname);
			$copied = copy($_FILES['cons_image']['tmp_name'], $consname2);
			$query = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE `bannerORIGINAL` NOT NULL AND `bannerTHUMB` NOT NULL AND `agent_id` = {$_SESSION['user_id']}";
			$result = mysql_query($query);
			if($result == 0) {
				$sql = "INSERT INTO agent_settings (bannerORIGINAL, bannerTHUMB) VALUES ('$consname', '$consname2') WHERE agent_id = {$_SESSION['user_id']}";
				mysql_query($sql);
			}else{
				$sql = "UPDATE `agent_settings` SET `bannerORIGINAL` = '$consname', `bannerTHUMB` = '$consname2' WHERE `agent_id` = {$_SESSION['user_id']}";
				$query = mysql_query($sql)or die(mysql_error());

				//we verify if the image has been uploaded, and print error instead
				if (!$copied) {
					echo 'Copy unsuccessfull!';
					$errors = 1;
				}else{
					// the new thumbnail image will be placed in images/thumbs/ folder
					$thumb_name = $consname2 ;
					// call the function that will create the thumbnail. The function will get as parameters
					//the image name, the thumbnail name and the width and height desired for the thumbnail
					$thumb = make_thumb($consname, $thumb_name, WIDTH, HEIGHT);
					$thumb = make_thumb($consname, $consname, WIDTH2, HEIGHT2);
				}
			}

  • 0

Just for reference here is my latest build of the code... I knows I still have errors but I posted this in fragments as of late.

<?
set_time_limit(0);
include 'dbc.php';
include 'sessions.php';
page_protect();

//define a maxim size for the uploaded images
define ("MAX_SIZE", "500");
// define the width and height for the thumbnail
// note that theese dimmensions are considered the maximum dimmension and are not fixed,
// because we have to keep the image ratio intact or it will be deformed
define ("WIDTH", "150"); //set here the width you want your thumbnail to be
define ("HEIGHT", "150"); //set here the height you want your thumbnail to be.
define ("WIDTH2", "299"); //set here the width you want your thumbnail to be
define ("HEIGHT2", "299"); //set here the height you want your thumbnail to be.
// this is the function that will create the thumbnail image from the uploaded image
// the resize will be done considering the width and
//height defined, but without deforming the image
function make_thumb($img_name, $filename, $new_w, $new_h){
	//get image extension.
	$ext = getExtension($img_name);
	//creates the new image using the appropriate function from gd library
	if(!strcmp("jpg", $ext) || !strcmp("jpeg", $ext))
		$src_img = imagecreatefromjpeg($img_name);
	if(!strcmp("png", $ext))
		$src_img = imagecreatefrompng($img_name);
	if(!strcmp("gif", $ext))
		$src_img = imagecreatefromgif($img_name);
	//gets the dimmensions of the image
	$old_x = imageSX($src_img);
	$old_y = imageSY($src_img);
	// next we will calculate the new dimmensions for the thumbnail image
	// the next steps will be taken:
	// 1. calculate the ratio by dividing the old dimmensions with the new ones
	// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
	// and the height will be calculated so the image ratio will not change
	// 3. otherwise we will use the height ratio for the image
	// as a result, only one of the dimmensions will be from the fixed ones
	$ratio1 = $old_x / $new_w;
	$ratio2 = $old_y / $new_h;
	if($ratio1 > $ratio2) {
		$thumb_w = $new_w;
		$thumb_h = $old_y / $ratio1;
	}else{
		$thumb_h = $new_h;
		$thumb_w = $old_x / $ratio2;
	}
	// we create a new image with the new dimmensions
	$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);
	// resize the big image to the new created one
	imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);
	// output the created image to the file. Now we will have the thumbnail into the file named by $filename
	if(!strcmp("png", $ext))
		imagepng($dst_img,$filename);
	else
		imagejpeg($dst_img,$filename);
	if (!strcmp("gif", $ext))
		imagegif($dst_img,$filename);
	//destroys source and destination images.
	imagedestroy($dst_img);
	imagedestroy($src_img);
}
// This function reads the extension of the file.
// It is used to determine if the file is an image by checking the extension.
function getExtension($str) {
	$i = strrpos($str, ".");
	if (!$i) { return ""; }
	$l = strlen($str) - $i;
	$ext = substr($str, $i + 1, $l);
	return $ext;
}
// This variable is used as a flag. The value is initialized with 0 (meaning no error found)
// and it will be changed to 1 if an error occures. If the error occures the file will not be uploaded.
$errors = 0;
// checks if the form has been submitted
if(isset($_POST['Submit'])) {
	//reads the name of the file the user submitted for uploading
	$image=$_FILES['cons_image']['name'];
	// if it is not empty
	if ($image) {
		// get the original name of the file from the clients machine
		$filename = stripslashes($_FILES['cons_image']['name']);
		// get the extension of the file in a lower case format
		$extension = getExtension($filename);
		$extension = strtolower($extension);
		// if it is not a known extension, we will suppose it is an error, print an error message
		// and will not upload the file, otherwise we continue
		if (($extension != "jpg") && ($extension != "jpeg") && ($extension != "png") && ($extension != "gif")) {
			echo 'Unknown extension! Please use .gif, .jpg or .png files only.';
			$errors = 1;
		}else{
			// get the size of the image in bytes
			// $_FILES[\'image\'][\'tmp_name\'] is the temporary filename of the file in which
			//the uploaded file was stored on the server
			$size = getimagesize($_FILES['cons_image']['tmp_name']);
			$sizekb = filesize($_FILES['cons_image']['tmp_name']);
			//compare the size with the maxim size we defined and print error if bigger
			if ($sizekb > MAX_SIZE*1024) {
				echo 'You have exceeded the 1MB size limit! <br/>';
				$errors = 1;
			}
			$rand = rand(0, 1000);
			//we will give an unique name, for example a random number
			$image_name = $rand . '.' . $extension;
			//the new name will be containing the full path where it will be stored (images folder)
			//location to where the original image will be uploaded to
			$consname = "/uploads/" . $username . "/images/banner/" . $image_name;
			//location to where the thumbnail image will be uploaded to
			$consname2 = "/uploads/" . $username . "/images/banner/thumbs/" . $image_name;
			$copied = copy($_FILES['cons_image']['tmp_name'], $consname);
			$copied = copy($_FILES['cons_image']['tmp_name'], $consname2);
			$query = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE `bannerORIGINAL` IS NOT NULL AND `bannerTHUMB` IS NOT NULL AND `agent_id` = {$_SESSION['user_id']}";
			$result = mysql_query($query);
			if($result < 1) {
				$sql = "INSERT INTO agent_settings (bannerORIGINAL, bannerTHUMB) VALUES ('$consname', '$consname2') WHERE agent_id = {$_SESSION['user_id']}";
				$query = mysql_query($sql);
			}else{
				$sql = "UPDATE `agent_settings` SET `bannerORIGINAL` = '$consname', `bannerTHUMB` = '$consname2' WHERE `agent_id` = {$_SESSION['user_id']}";
				$query = mysql_query($sql)or die(mysql_error());
			}
			//we verify if the image has been uploaded, and print error instead
			if (!$copied) {
				echo 'Copy unsuccessful!<br />';
				echo $consname; // just checking to see if its being concatinated correctly.
				$errors = 1;
			}else{
				// the new thumbnail image will be placed in images/thumbs/ folder
				$thumb_name = $consname2 ;
				// call the function that will create the thumbnail. The function will get as parameters
				//the image name, the thumbnail name and the width and height desired for the thumbnail
				$thumb = make_thumb($consname, $thumb_name, WIDTH, HEIGHT);
				$thumb = make_thumb($consname, $consname, WIDTH2, HEIGHT2);
			}
		}
	}
}
//If no errors registred, print the success message and how the thumbnail image created
if(isset($_POST['Submit']) && !$errors) {
	echo "Thumbnail created Successfully!";
	echo '< img src="'.$thumb_name.'">';
	echo $lastid;
}
//echo $username;
//echo $consname;
//echo $consname2;

?>
<form name="newad" method="post" enctype="multipart/form-data" action="">
<input type="file" name="cons_image" />
<input name="Submit" type="submit" id="image1" value="Upload image" />
</form>

  • 0

Okay, I've done a lot of work to tidy things up...

<?

// Set default timezone (New PHP versions complain without this!)

	date_default_timezone_set("GMT");

// Common

	set_time_limit(0);

	require_once('dbc.php');
	require_once('sessions.php');

	page_protect();

// Image settings

	define('IMG_FIELD_NAME', 'cons_image');

	// Max upload size in bytes (for form)
	define ('MAX_SIZE_IN_BYTES', '512000');

	// Width and height for the thumbnail
	define ('THUMB_WIDTH', '150');
	define ('THUMB_HEIGHT', '150');

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
	<title>whatever</title>
	<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
	<style type="text\css">
		.validationErrorText { color:red; font-size:85%; font-weight:bold; }
	</style>
</head>
<body>
	<h1>Change image</h1>
<?php

$errors = array();

// Process form
if (isset($_POST['submit'])) {

	// Get filename
	$filename = stripslashes($_FILES['cons_image']['name']);

	// Validation of image file upload
	$allowedFileTypes = array('image/gif', 'image/jpg', 'image/jpeg', 'image/png');
	if ($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_NO_FILE) {

		$errors['img_empty'] = true;

	} elseif (($_FILES[IMG_FIELD_NAME]['type'] != '') && (!in_array($_FILES[IMG_FIELD_NAME]['type'], $allowedFileTypes))) {

		$errors['img_type'] = true;

	} elseif (($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_INI_SIZE) || ($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_FORM_SIZE) || ($_FILES[IMG_FIELD_NAME]['size'] > MAX_SIZE_IN_BYTES)) {

		$errors['img_size'] = true;

	} elseif ($_FILES[IMG_FIELD_NAME]['error'] != UPLOAD_ERR_OK) {

		$errors['img_error'] = true;

	} elseif (strlen($_FILES[IMG_FIELD_NAME]['name']) > 200) {

		$errors['img_nametoolong'] = true;

	} elseif ( (file_exists(__DIR__ . "\uploads\$username\images\banner\$filename")) || (file_exists(__DIR__ . "\uploads\$username\images\banner\thumbs\$filename")) ) {

		$errors['img_fileexists'] = true;
	}

	if (! empty($errors)) { 
		unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
	}

	// Create thumbnail
	if (empty($errors)) {

		// Move uploaded file to final destination
		if (! move_uploaded_file($_FILES[IMG_FIELD_NAME]['tmp_name'], "/uploads/$username/images/banner/$filename")) {
			$errors['move_source'];
			unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
		} else {

			// Create thumbnail in new dir
			if (! make_thumb("/uploads/$username/images/banner/$filename", "/uploads/$username/images/banner/thumbs/$filename")) {
				$errors['thumb'];
				unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
			}
		}
	}

	// Record in database
	if (empty($errors)) {

		// Find existing record and delete existing images
		$sql = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE (`agent_id`={$_SESSION['user_id']}) LIMIT 1";
		$result = mysql_query($sql);
		if (!$result) {
			unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
			unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
			die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
		}
		$numResults = mysql_num_rows($result);
		if ($numResults == 1) {
			$row = mysql_fetch_assoc($result);

			// Delete old files
			unlink("/uploads/$username/images/banner/" . $row['bannerORIGINAL']); //delete OLD source file
			unlink("/uploads/$username/images/banner/thumbs/" . $row['bannerTHUMB']); //delete OLD thumbnail file
		}

		// Update/create record with new images
		if ($numResults == 1) {
			$sql = "INSERT INTO `agent_settings` (`agent_id`, `bannerORIGINAL`, `bannerTHUMB`) VALUES ({$_SESSION['user_id']}, '/uploads/$username/images/banner/$filename', '/uploads/$username/images/banner/thumbs/$filename')";
		} else {
			$sql = "UPDATE `agent_settings` SET `bannerORIGINAL`='/uploads/$username/images/banner/$filename', `bannerTHUMB`='/uploads/$username/images/banner/thumbs/$filename' WHERE (`agent_id`={$_SESSION['user_id']})";
		}
		$result = mysql_query($sql);
		if (!$result) {
			unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
			unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
			die("<div><b>Error: Problem occurred with Database Query!</b><br /><br /><b>File:</b> " . __FILE__ . "<br /><b>Line:</b> " . __LINE__ . "<br /><b>MySQL Error Num:</b> " . mysql_errno() . "<br /><b>MySQL Error:</b> " . mysql_error() . "</div>");
		}
        }

	// Print success message and how the thumbnail image created
	if (empty($errors)) {
	        echo "<p>Thumbnail created Successfully!</p>\n";
        	echo "<img src=\"/uploads/$username/images/banner/thumbs/$filename" alt=\"New image thumbnail\" />\n";
		echo "<br />\n";
	}
}
if (isset($errors['move_source'])) { echo "\t\t<div>Error: Failure occurred moving uploaded source image!</div>\n"; }
if (isset($errors['thumb'])) { echo "\t\t<div>Error: Failure occurred creating thumbnail!</div>\n"; }
?>
	<form action="" enctype="multipart/form-data" method="post">
		<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo MAX_SIZE_IN_BYTES; ?>" />
		<label for="cons_image">Image:</label> <input type="file" name="cons_image" id="cons_image" />
<?php
if (isset($errors['img_empty'])) { echo "\t\t<div class=\"validationErrorText\">Required!</div>\n"; }
if (isset($errors['img_type'])) { echo "\t\t<div class=\"validationErrorText\">File type not allowed! GIF/JPEG/PNG only!</div>\n"; }
if (isset($errors['img_size'])) { echo "\t\t<div class=\"validationErrorText\">File size too large! Maximum size should be " . MAX_SIZE_IN_BYTES . "bytes!</div>\n"; }
if (isset($errors['img_error'])) { echo "\t\t<div class=\"validationErrorText\">File upload error occured! Error code: {$_FILES[IMG_FIELD_NAME]['error']}</div>\n"; }
if (isset($errors['img_nametoolong'])) { echo "\t\t<div class=\"validationErrorText\">Filename too long! 200 Chars max!</div>\n"; }
if (isset($errors['img_fileexists'])) { echo "\t\t<div class=\"validationErrorText\">An image file already exists with that name!</div>\n"; }
?>
		<br /><input type="submit" name="submit" id="image1" value="Upload image" />
	</form>
</body>
</html>
<?php

#################################
#
#      F U N C T I O N S
#
#################################

/*
 *  Function: make_thumb
 *
 *  Creates the thumbnail image from the uploaded image
 *  the resize will be done considering the width and
 *  height defined, but without deforming the image
 *
 *  @param   $sourceFile   Path anf filename of source image
 *  @param   $destFile     Path and filename to save thumbnail as
 *  @param   $new_w        the new width to use
 *  @param   $new_h        the new height to use
*/
function make_thumb($sourceFile, $destFile, $new_w=false, $new_h=false)
{
	if ($new_w === false) { $new_w = THUMB_WIDTH; }
	if ($new_h === false) { $new_h = THUMB_HEIGHT; }

	// Get image extension
	$ext = strtolower(getExtension($img_name));

	// Copy source
	switch($ext) {
		case 'jpg':
		case 'jpeg':
			$img_src = imagecreatefromjpeg($sourceFile);
			break;
		case 'png':
			$img_src = imagecreatefrompng($sourceFile);
			break;
		case 'gif':
			$img_src = imagecreatefromgif($sourceFile);
			break;
		default:
			return false;
	}
	if (!$img_src) { return false; }

	// Get dimmensions of the source image
	$old_x = imageSX($src_img);
	$old_y = imageSY($src_img);

	// Calculate the new dimmensions for the thumbnail image
	// 1. calculate the ratio by dividing the old dimmensions with the new ones
	// 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
 	//    and the height will be calculated so the image ratio will not change
	// 3. otherwise we will use the height ratio for the image
	//    as a result, only one of the dimmensions will be from the fixed ones
	$ratio1 = $old_x / $new_w;
	$ratio2 = $old_y / $new_h;
	if ($ratio1 > $ratio2) {
		$thumb_w = $new_w;
		$thumb_h = $old_y / $ratio1;
	} else {
		$thumb_h = $new_h;
		$thumb_w = $old_x / $ratio2;
	}

	// Create a new image with the new dimmensions
	$dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);

	// Resize the big image to the new created one
	imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);

	// Output the created image to the file. Now we will have the thumbnail into the file named by $filename
	switch($ext) {
		case 'jpg':
		case 'jpeg':
			$result = imagepng($dst_img, $destFile);
			break;
		case 'png':
			$result = imagegif($dst_img, $destFile);
			break;
		case 'gif':
			$result = imagejpeg($dst_img, $destFile);
			break;
		default:
			//should never occur!
	}
	if (!$result) { return false; }

	// Destroy source and destination images
	imagedestroy($dst_img);
	imagedestroy($src_img);

	return true;
}

/*
 *  Function: getExtension
 *
 *  Returns the file extension from a given filename/path
 *
 *  @param   $str   the filename to get the extension from
*/
function getExtension($str)
{
	return pathinfo($filename, PATHINFO_EXTENSION);
}

?>

There still could be issues with it, I haven't actually run the code.

One definite problem is using $_FILES['whatever']['type'] to check the filetype. The filetype specified is given by the browser, and so cannot be trusted. There is a more secure way, by using 'fileinfo', but it's only become a standard part of PHP in version 5.3, and I don't know if you have that, for some older versions an extension is available. Btw, the way you were doing it, by checking the extension, is just as bad as how I'm doing it, just because my file is called "virus.exe.jpg", does not mean it's safe!

I stripped out the code to do with creating a random name, you were simply choosing a random number from 0 to 1000, and just assuming there was no existing image with that filename. It wasn't really necessary to do any of this at all, so I got rid of it. User's images are stored within their own directory within /uploads/, and now, if an image already exists with the same filename as the new image, you'll get a warning about it and have to upload with a different filename. This behaviour could be changed however if the only images being stored are the ones we're replacing anyway.

Someone owes me a beer ;)

I hope this isn't college/uni work btw, if it is I've done far too much!

  • 0

hey, i was looking at the code

for the links to the folders, aren't we suppose to concatinate the variables? like

"/uploads/" . $username . "/images/banner/" . $filename

also isn 't it the same for the SQL query? so the variables could be passes correctly into the query no?

I thought it might make more sense right?

my register script has it so it makes all the tables and fields for a specific user so that the anget_id matches on all the tables with the agnet_id field in them to check against...

I ran the script and got an error with the sql query, my suspicion was that the INSERT INTO query was wrong... maybe, still get an error but it just refferes me to line 128 which is the error output line in the code

} $sql = "INSERT INTO `agent_settings` (`bannerORIGINAL`, `bannerTHUMB`) VALUES ('/uploads/$username/images/banner/$filename', '/uploads/$username/images/banner/thumbs/$filename') WHERE (`agent_id` = {$_SESSION['user_id']})";

Change image

Error: Problem occurred with Database Query!

File: /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload.php

Line: 128

MySQL Error Num: 1064

MySQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE (`agent_id` = 1)' at line 1

  • 0

hey, i was looking at the code

for the links to the folders, aren't we suppose to concatinate the variables? like

"/uploads/" . $username . "/images/banner/" . $filename

no, if a string is enclosed in double quotes (e.g. "string", not 'string') then PHP will parse it looking for variables. Watch out though, a variable called $age in "i am $ageyrs old" will be treated as $ageyrs, and array entries cannot be accessed; To get around this, enclose in curly braces, e.g. "i am {$age}yrs old", or "i am {$userdata['age']}yrs old". Oh, for constants you must always concatenate though! (i.e. echo "i am " . MY_AGE . "yrs old"; )

um, also I dunno if i just messed up your hard work but I changed this

} else {
                    	$sql = "UPDATE `agent_settings` SET `bannerORIGINAL`='/uploads/$username/images/banner/$filename', `bannerTHUMB`='/uploads/$username/images/banner/thumbs/$filename' WHERE (`agent_id` = {$user_id})";

that's fine, so long as $user_id exists and contains the correct userID.

my register script has it so it makes all the tables and fields for a specific user so that the anget_id matches on all the tables with the agnet_id field in them to check against...

Sorry, what? You haven't got actual separate tables for each user do you? I think (hope) I'm just misunderstanding you, your code so far has thankfully not suggested your doing something like that.

I ran the script and got an error with the sql query, my suspicion was that the UPDATE query was wrong... maybe, so I changed it to that, still get an error but it just refferes me to line 128 which is the error output line in the code

Yes, the line number comes from whatever line "__LINE__" is on, which, if it were to be placed on the very same line as the actual SQL query, would make the code very messy. Just use it as a guide, it tells you where the error was printed, so just look up a few lines and you'll find the SQL query the error printing code belongs to!

In this case the error is reported for line 128, so comes from SQL on line 119 or 121 (depending on the outcome of the IF statement).

I don't know what the problem is because I don't have a copy of your database and other code.

Stick

echo $sql;

after the SQL (after the if statement, so put it on line 123) and it'll display on the page the exact full sql query that's being run, this should help you figure out the cause. If you can't figure it out, i'll need the database, and perhaps all the rest of the code.

  • 0

No no no

I don't have a table for each user, I have a row filed with data I'll later be using

like

usersTable

user_id, name, username, pass, etc

settingsTable

user_id, bannerOR, bannerTH, etc. <- al my settings will go here... unless you have a more simple way to organize the settings. Such as language, images for backgrounds, or css themes and such.

i just make usre that user_id from usersTable is created in a session variable to equal $user_id, i should of used that variable but i forgot I made it in my sessions.php wink.gif but any ways, that $user_id should euqal user_id in the table that i'm inserting or updating into...

I'm learning, and I bet there are other more preferred methods to have multiple tables where one row belongs to a specific user and such, but for me this is how I thought I could do it...

still not getting the hand of foreing id's btw so i havne't used them....yet...

oh, I ran the INSERT INTO query in the myPHPAdmin SQL thing, and it returns an error with me manually setting {$user_id} as 1 (1 is the id of my test user).

I looked online and didn't find any errors in that query, so i'm still wondering...what the heck?!?! pinch.gif

oh and this is my sql for my settings table too

CREATE TABLE IF NOT EXISTS `agent_settings` (
  `agent_id` int(11) NOT NULL default '0',
  `settings_id` int(11) NOT NULL auto_increment,
  `bannerORIGINAL` text character set utf8 NOT NULL,
  `bannerTHUMB` text character set utf8 NOT NULL,
  PRIMARY KEY  (`settings_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=greek AUTO_INCREMENT=4 ;

  • 0

Good good

If you only have one record in agent_settings per record in the users table, then really the data your storing in agent_settings should be stored in the users table itself, but don;t worry about that, you can work on fixing that later, you're just learning

Foreign keys, well you're already using foreign keys by including the user_id (id of the user record) in the agent_settings record. What you're not doing yet is setting up referential integrity, which means you can do stuff like: if you ever change the user_id, the id in other tables will be automatically updated to match; or if you delete the user record, all records related to it will automatically be deleted.

Note, to set this up you need your database tables to be using a 'database engine' that supports referential integrity! MySQL has several engines, MyISAM is the default and does NOT support this, you'll need to use the InnoDB engine! Note 'MyISAM' in your table creation SQL code!

As for the error, I can't tell what's causing it, and need all the rest of the code and any other tables referenced (i.e. users table) in order to figure it out.

OR, do what i said previously and stick "echo $sql;" in at line #123, then try again, it'll display the complete SQL query that's being attempted on the page, copy and paste that here for me, i should be able to figure it out from that!

Oh, note that on lines 119 and 121 you might also want to change {$_SESSION['user_id']} to {$user_id} like the other query you mentioned

  • 0

Good good

If you only have one record in agent_settings per record in the users table, then really the data your storing in agent_settings should be stored in the users table itself, but don;t worry about that, you can work on fixing that later, you're just learning

Foreign keys, well you're already using foreign keys by including the user_id (id of the user record) in the agent_settings record. What you're not doing yet is setting up referential integrity, which means you can do stuff like: if you ever change the user_id, the id in other tables will be automatically updated to match; or if you delete the user record, all records related to it will automatically be deleted.

Note, to set this up you need your database tables to be using a 'database engine' that supports referential integrity! MySQL has several engines, MyISAM is the default and does NOT support this, you'll need to use the InnoDB engine! Note 'MyISAM' in your table creation SQL code!

As for the error, I can't tell what's causing it, and need all the rest of the code and any other tables referenced (i.e. users table) in order to figure it out.

OR, do what i said previously and stick "echo $sql;" in at line #123, then try again, it'll display the complete SQL query that's being attempted on the page, copy and paste that here for me, i should be able to figure it out from that!

Oh, note that on lines 119 and 121 you might also want to change {$_SESSION['user_id']} to {$user_id} like the other query you mentioned

Ya, my hosted myPHPAdmin on my host doesn't support InnoDB ;( so I'll have to make due until I can move to a dedicated server and I'll setup myPHPAdmin will all functionalities then...

hmm, ya I went and changed the session variables to my custom defined php variable. hmmm, ya it thought about that too. But I just figured if a user deletes their account or if i delete their acount, i'll run a DROP query for every row that has a field whose id matches the uers id that is being dropped... kinda repetetive but oh well, right?

Oh, well I copied your modified code and i saw that If I comment out the WHERE clause in the INSERT INTO statement that everything will follow and output as such. but um... the problem is that the file I upload isn't actually being uploaded to my server, I have set all the folders+the uploads folder to 0777 for now. still didn't work heh.

hey i made a test account

test/test

you can try login in and see how it behaves.

www.helixagent.com

when you log in, in the url go to /upload.php.

/upload2.php has the commented out WHERE clause, this one will work with no sql errors...

try to upload something and you'll see what its doing. I included the echo statements in both the INSERT and UPDATE areas.

  • 0

Oh hang on, I'm an idiot, you changed the insert query earlier, and I completely missed that you added a where clause to it, and why that was significant. Take the where clause off, you never need a where clause on an insert statement!

Okay, I've run the code now on my machine and corrected a few little bugs. It now correctly identifies that a problem occurred, and the code turns on PHP error reporting (probably disabled by default by your host), so we can see the errors.

&lt;?php

//Temporarily turn on error reporting
@ini_set('display_errors', 1);
error_reporting(E_ALL);

// Set default timezone (New PHP versions complain without this!)

        date_default_timezone_set("GMT");

// Common

        set_time_limit(0);

        require_once('dbc.php');
        require_once('sessions.php');

        page_protect();

// Image settings

        define('IMG_FIELD_NAME', 'cons_image');

        // Max upload size in bytes (for form)
        define ('MAX_SIZE_IN_BYTES', '512000');

        // Width and height for the thumbnail
        define ('THUMB_WIDTH', '150');
        define ('THUMB_HEIGHT', '150');

?&gt;
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"&gt;
&lt;head&gt;
        &lt;title&gt;whatever&lt;/title&gt;
        &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt;
        &lt;style type="text\css"&gt;
                .validationerrorText { color:red; font-size:85%; font-weight:bold; }
        &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
        &lt;h1&gt;Change image&lt;/h1&gt;
&lt;?php

$errors = array();

// Process form
if (isset($_POST['submit'])) {

        // Get filename
        $filename = stripslashes($_FILES['cons_image']['name']);
var_dump($_FILES);
        // Validation of image file upload
        $allowedFileTypes = array('image/gif', 'image/jpg', 'image/jpeg', 'image/png');
        if ($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_NO_FILE) {

                $errors['img_empty'] = true;

        } elseif (($_FILES[IMG_FIELD_NAME]['type'] != '') &amp;&amp; (!in_array($_FILES[IMG_FIELD_NAME]['type'], $allowedFileTypes))) {

                $errors['img_type'] = true;

        } elseif (($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_INI_SIZE) || ($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_FORM_SIZE) || ($_FILES[IMG_FIELD_NAME]['size'] &gt; MAX_SIZE_IN_BYTES)) {

                $errors['img_size'] = true;

        } elseif ($_FILES[IMG_FIELD_NAME]['error'] != UPLOAD_ERR_OK) {

                $errors['img_error'] = true;

        } elseif (strlen($_FILES[IMG_FIELD_NAME]['name']) &gt; 200) {

                $errors['img_nametoolong'] = true;

        } elseif ( (file_exists(__DIR__ . "\uploads\$username\images\banner\$filename")) || (file_exists(__DIR__ . "\uploads\$username\images\banner\thumbs\$filename")) ) {

                $errors['img_fileexists'] = true;
        }

        if (! empty($errors)) { 
                unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
        }

        // Create thumbnail
        if (empty($errors)) {

                // Move uploaded file to final destination
                if (! move_uploaded_file($_FILES[IMG_FIELD_NAME]['tmp_name'], "/uploads/$username/images/banner/$filename")) {
                        $errors['move_source'] = true;
                        unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
                } else {

                        // Create thumbnail in new dir
                        if (! make_thumb("/uploads/$username/images/banner/$filename", "/uploads/$username/images/banner/thumbs/$filename")) {
                                $errors['thumb'];
                                unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
                        }
                }
        }

        // Record in database
        if (empty($errors)) {

                // Find existing record and delete existing images
                $sql = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE (`agent_id`={$user_id}) LIMIT 1";
                $result = mysql_query($sql);
                if (!$result) {
                        unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
                        unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
                        die("&lt;div&gt;&lt;b&gt;Error: Problem occurred with Database Query!&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;File:&lt;/b&gt; " . __FILE__ . "&lt;br /&gt;&lt;b&gt;Line:&lt;/b&gt; " . __LINE__ . "&lt;br /&gt;&lt;b&gt;MySQL Error Num:&lt;/b&gt; " . mysql_errno() . "&lt;br /&gt;&lt;b&gt;MySQL Error:&lt;/b&gt; " . mysql_error() . "&lt;/div&gt;");
                }
                $numResults = mysql_num_rows($result);
                if ($numResults == 1) {
                        $row = mysql_fetch_assoc($result);

                        // Delete old files
                        unlink("/uploads/$username/images/banner/" . $row['bannerORIGINAL']); //delete OLD source file
                        unlink("/uploads/$username/images/banner/thumbs/" . $row['bannerTHUMB']); //delete OLD thumbnail file
                }

                // Update/create record with new images
                if ($numResults == 1) {
                        $sql = "INSERT INTO `agent_settings` (`agent_id`, `bannerORIGINAL`, `bannerTHUMB`) VALUES ({$user_id}, '/uploads/$username/images/banner/$filename', '/uploads/$username/images/banner/thumbs/$filename')";
                } else {
                        $sql = "UPDATE `agent_settings` SET `bannerORIGINAL`='/uploads/$username/images/banner/$filename', `bannerTHUMB`='/uploads/$username/images/banner/thumbs/$filename' WHERE (`agent_id`={$user_id})";
                }
                $result = mysql_query($sql);
                if (!$result) {
                        unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
                        unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
                        die("&lt;div&gt;&lt;b&gt;Error: Problem occurred with Database Query!&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;File:&lt;/b&gt; " . __FILE__ . "&lt;br /&gt;&lt;b&gt;Line:&lt;/b&gt; " . __LINE__ . "&lt;br /&gt;&lt;b&gt;MySQL Error Num:&lt;/b&gt; " . mysql_errno() . "&lt;br /&gt;&lt;b&gt;MySQL Error:&lt;/b&gt; " . mysql_error() . "&lt;/div&gt;");
                }
        }

        // Print success message and how the thumbnail image created
        if (empty($errors)) {
                echo "&lt;p&gt;Thumbnail created Successfully!&lt;/p&gt;\n";
                echo "&lt;img src=\"/uploads/$username/images/banner/thumbs/$filename\" alt=\"New image thumbnail\" /&gt;\n";
                echo "&lt;br /&gt;\n";
        }
}
if (isset($errors['move_source'])) { echo "\t\t&lt;div&gt;Error: Failure occurred moving uploaded source image!&lt;/div&gt;\n"; }
if (isset($errors['thumb'])) { echo "\t\t&lt;div&gt;Error: Failure occurred creating thumbnail!&lt;/div&gt;\n"; }
?&gt;
        &lt;form action="" enctype="multipart/form-data" method="post"&gt;
                &lt;input type="hidden" name="MAX_FILE_SIZE" value="&lt;?php echo MAX_SIZE_IN_BYTES; ?&gt;" /&gt;
                &lt;label for="&lt;?php echo IMG_FIELD_NAME; ?&gt;"&gt;Image:&lt;/label&gt; &lt;input type="file" name="&lt;?php echo IMG_FIELD_NAME; ?&gt;" id="&lt;?php echo IMG_FIELD_NAME; ?&gt;" /&gt;
&lt;?php
if (isset($errors['img_empty'])) { echo "\t\t&lt;div class=\"validationerrorText\"&gt;Required!&lt;/div&gt;\n"; }
if (isset($errors['img_type'])) { echo "\t\t&lt;div class=\"validationerrorText\"&gt;File type not allowed! GIF/JPEG/PNG only!&lt;/div&gt;\n"; }
if (isset($errors['img_size'])) { echo "\t\t&lt;div class=\"validationerrorText\"&gt;File size too large! Maximum size should be " . MAX_SIZE_IN_BYTES . "bytes!&lt;/div&gt;\n"; }
if (isset($errors['img_error'])) { echo "\t\t&lt;div class=\"validationerrorText\"&gt;File upload error occured! Error code: {$_FILES[IMG_FIELD_NAME]['error']}&lt;/div&gt;\n"; }
if (isset($errors['img_nametoolong'])) { echo "\t\t&lt;div class=\"validationerrorText\"&gt;Filename too long! 200 Chars max!&lt;/div&gt;\n"; }
if (isset($errors['img_fileexists'])) { echo "\t\t&lt;div class=\"validationerrorText\"&gt;An image file already exists with that name!&lt;/div&gt;\n"; }
?&gt;
                &lt;br /&gt;&lt;input type="submit" name="submit" id="image1" value="Upload image" /&gt;
        &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
&lt;?php

#################################
#
#      F U N C T I O N S
#
#################################

/*
 *  Function: make_thumb
 *
 *  Creates the thumbnail image from the uploaded image
 *  the resize will be done considering the width and
 *  height defined, but without deforming the image
 *
 *  @param   $sourceFile   Path anf filename of source image
 *  @param   $destFile     Path and filename to save thumbnail as
 *  @param   $new_w        the new width to use
 *  @param   $new_h        the new height to use
*/
function make_thumb($sourceFile, $destFile, $new_w=false, $new_h=false)
{
        if ($new_w === false) { $new_w = THUMB_WIDTH; }
        if ($new_h === false) { $new_h = THUMB_HEIGHT; }

        // Get image extension
        $ext = strtolower(getExtension($img_name));

        // Copy source
        switch($ext) {
                case 'jpg':
                case 'jpeg':
                        $img_src = imagecreatefromjpeg($sourceFile);
                        break;
                case 'png':
                        $img_src = imagecreatefrompng($sourceFile);
                        break;
                case 'gif':
                        $img_src = imagecreatefromgif($sourceFile);
                        break;
                default:
                        return false;
        }
        if (!$img_src) { return false; }

        // Get dimmensions of the source image
        $old_x = imageSX($src_img);
        $old_y = imageSY($src_img);

        // Calculate the new dimmensions for the thumbnail image
        // 1. calculate the ratio by dividing the old dimmensions with the new ones
        // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
        //    and the height will be calculated so the image ratio will not change
        // 3. otherwise we will use the height ratio for the image
        //    as a result, only one of the dimmensions will be from the fixed ones
        $ratio1 = $old_x / $new_w;
        $ratio2 = $old_y / $new_h;
        if ($ratio1 &gt; $ratio2) {
                $thumb_w = $new_w;
                $thumb_h = $old_y / $ratio1;
        } else {
                $thumb_h = $new_h;
                $thumb_w = $old_x / $ratio2;
        }

        // Create a new image with the new dimmensions
        $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);

        // Resize the big image to the new created one
        imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);

        // Output the created image to the file. Now we will have the thumbnail into the file named by $filename
        switch($ext) {
                case 'jpg':
                case 'jpeg':
                        $result = imagepng($dst_img, $destFile);
                        break;
                case 'png':
                        $result = imagegif($dst_img, $destFile);
                        break;
                case 'gif':
                        $result = imagejpeg($dst_img, $destFile);
                        break;
                default:
                        //should never occur!
        }
        if (!$result) { return false; }

        // Destroy source and destination images
        imagedestroy($dst_img);
        imagedestroy($src_img);

        return true;
}

/*
 *  Function: getExtension
 *
 *  Returns the file extension from a given filename/path
 *
 *  @param   $str   the filename to get the extension from
*/
function getExtension($str)
{
        return pathinfo($filename, PATHINFO_EXTENSION);
}

?&gt;

  • 0

^ precisely, in an update query, you're modifying the data in an existing record, you need to specify the ID of the record to update with a where clause else it'll replace the data in EVERY record. with insert, you're simply creating a new record in the table, so no need for a where clause, you understand... ?

a couple further fixes:

&lt;?php

//Temporarily turn on error reporting
@ini_set('display_errors', 1);
error_reporting(E_ALL);

// Set default timezone (New PHP versions complain without this!)

        date_default_timezone_set("GMT");

// Common

        set_time_limit(0);

        require_once('dbc.php');
        require_once('sessions.php');

        page_protect();

// Image settings

        define('IMG_FIELD_NAME', 'cons_image');

        // Max upload size in bytes (for form)
        define ('MAX_SIZE_IN_BYTES', '512000');

        // Width and height for the thumbnail
        define ('THUMB_WIDTH', '150');
        define ('THUMB_HEIGHT', '150');

?&gt;
&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"&gt;
&lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"&gt;
&lt;head&gt;
        &lt;title&gt;whatever&lt;/title&gt;
        &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /&gt;
        &lt;style type="text\css"&gt;
                .validationerrorText { color:red; font-size:85%; font-weight:bold; }
        &lt;/style&gt;
&lt;/head&gt;
&lt;body&gt;
        &lt;h1&gt;Change image&lt;/h1&gt;
&lt;?php

$errors = array();

// Process form
if (isset($_POST['submit'])) {

        // Get filename
        $filename = stripslashes($_FILES['cons_image']['name']);

        // Validation of image file upload
        $allowedFileTypes = array('image/gif', 'image/jpg', 'image/jpeg', 'image/png');
        if ($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_NO_FILE) {

                $errors['img_empty'] = true;

        } elseif (($_FILES[IMG_FIELD_NAME]['type'] != '') &amp;&amp; (!in_array($_FILES[IMG_FIELD_NAME]['type'], $allowedFileTypes))) {

                $errors['img_type'] = true;

        } elseif (($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_INI_SIZE) || ($_FILES[IMG_FIELD_NAME]['error'] == UPLOAD_ERR_FORM_SIZE) || ($_FILES[IMG_FIELD_NAME]['size'] &gt; MAX_SIZE_IN_BYTES)) {

                $errors['img_size'] = true;

        } elseif ($_FILES[IMG_FIELD_NAME]['error'] != UPLOAD_ERR_OK) {

                $errors['img_error'] = true;

        } elseif (strlen($_FILES[IMG_FIELD_NAME]['name']) &gt; 200) {

                $errors['img_nametoolong'] = true;

        } elseif ( (file_exists(__DIR__ . "\\uploads\\$username\\images\\banner\\$filename")) || (file_exists(__DIR__ . "\\uploads\\$username\\images\\banner\\thumbs\\$filename")) ) {

                $errors['img_fileexists'] = true;
        }

        if (! empty($errors)) { 
                unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
        }

        // Create thumbnail
        if (empty($errors)) {

		// Make directory if it doesn't exist
		if ( (!is_dir("\\uploads\\$username\\images\\banner\\thumbs\\")) &amp;&amp; (!mkdir("\\uploads\\$username\\images\\banner\\thumbs\\")) ) {
                        $errors['move_source'] = true;
                        unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
		} else {
	                // Move uploaded file to final destination
	                if (! move_uploaded_file($_FILES[IMG_FIELD_NAME]['tmp_name'], "/uploads/$username/images/banner/$filename")) {
        	                $errors['move_source'] = true;
                	        unlink($_FILES[IMG_FIELD_NAME]['tmp_name']); //cleanup: delete temp file
               	 } else {

	                        // Create thumbnail in new dir
        	                if (! make_thumb("/uploads/$username/images/banner/$filename", "/uploads/$username/images/banner/thumbs/$filename")) {
                	                $errors['thumb'];
                        	        unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
                        	}
                	}
        	}
	}

        // Record in database
        if (empty($errors)) {

                // Find existing record and delete existing images
                $sql = "SELECT `bannerORIGINAL`, `bannerTHUMB` FROM `agent_settings` WHERE (`agent_id`={$user_id}) LIMIT 1";
                $result = mysql_query($sql);
                if (!$result) {
                        unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
                        unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
                        die("&lt;div&gt;&lt;b&gt;Error: Problem occurred with Database Query!&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;File:&lt;/b&gt; " . __FILE__ . "&lt;br /&gt;&lt;b&gt;Line:&lt;/b&gt; " . __LINE__ . "&lt;br /&gt;&lt;b&gt;MySQL Error Num:&lt;/b&gt; " . mysql_errno() . "&lt;br /&gt;&lt;b&gt;MySQL Error:&lt;/b&gt; " . mysql_error() . "&lt;/div&gt;");
                }
                $numResults = mysql_num_rows($result);
                if ($numResults == 1) {
                        $row = mysql_fetch_assoc($result);

                        // Delete old files
                        unlink("/uploads/$username/images/banner/" . $row['bannerORIGINAL']); //delete OLD source file
                        unlink("/uploads/$username/images/banner/thumbs/" . $row['bannerTHUMB']); //delete OLD thumbnail file
                }

                // Update/create record with new images
                if ($numResults == 1) {
                        $sql = "INSERT INTO `agent_settings` (`agent_id`, `bannerORIGINAL`, `bannerTHUMB`) VALUES ({$user_id}, '/uploads/$username/images/banner/$filename', '/uploads/$username/images/banner/thumbs/$filename')";
                } else {
                        $sql = "UPDATE `agent_settings` SET `bannerORIGINAL`='/uploads/$username/images/banner/$filename', `bannerTHUMB`='/uploads/$username/images/banner/thumbs/$filename' WHERE (`agent_id`={$user_id})";
                }
                $result = mysql_query($sql);
                if (!$result) {
                        unlink("/uploads/$username/images/banner/$filename"); //cleanup: delete source file
                        unlink("/uploads/$username/images/banner/thumbs/$filename"); //cleanup: delete thumbnail file
                        die("&lt;div&gt;&lt;b&gt;Error: Problem occurred with Database Query!&lt;/b&gt;&lt;br /&gt;&lt;br /&gt;&lt;b&gt;File:&lt;/b&gt; " . __FILE__ . "&lt;br /&gt;&lt;b&gt;Line:&lt;/b&gt; " . __LINE__ . "&lt;br /&gt;&lt;b&gt;MySQL Error Num:&lt;/b&gt; " . mysql_errno() . "&lt;br /&gt;&lt;b&gt;MySQL Error:&lt;/b&gt; " . mysql_error() . "&lt;/div&gt;");
                }
        }

        // Print success message and how the thumbnail image created
        if (empty($errors)) {
                echo "&lt;p&gt;Thumbnail created Successfully!&lt;/p&gt;\n";
                echo "&lt;img src=\"/uploads/$username/images/banner/thumbs/$filename\" alt=\"New image thumbnail\" /&gt;\n";
                echo "&lt;br /&gt;\n";
        }
}
if (isset($errors['move_source'])) { echo "\t\t&lt;div&gt;Error: Failure occurred moving uploaded source image!&lt;/div&gt;\n"; }
if (isset($errors['thumb'])) { echo "\t\t&lt;div&gt;Error: Failure occurred creating thumbnail!&lt;/div&gt;\n"; }
?&gt;
        &lt;form action="" enctype="multipart/form-data" method="post"&gt;
                &lt;input type="hidden" name="MAX_FILE_SIZE" value="&lt;?php echo MAX_SIZE_IN_BYTES; ?&gt;" /&gt;
                &lt;label for="&lt;?php echo IMG_FIELD_NAME; ?&gt;"&gt;Image:&lt;/label&gt; &lt;input type="file" name="&lt;?php echo IMG_FIELD_NAME; ?&gt;" id="&lt;?php echo IMG_FIELD_NAME; ?&gt;" /&gt;
&lt;?php
if (isset($errors['img_empty'])) { echo "\t\t&lt;div class=\"validationerrorText\"&gt;Required!&lt;/div&gt;\n"; }
if (isset($errors['img_type'])) { echo "\t\t&lt;div class=\"validationerrorText\"&gt;File type not allowed! GIF/JPEG/PNG only!&lt;/div&gt;\n"; }
if (isset($errors['img_size'])) { echo "\t\t&lt;div class=\"validationerrorText\"&gt;File size too large! Maximum size should be " . MAX_SIZE_IN_BYTES . "bytes!&lt;/div&gt;\n"; }
if (isset($errors['img_error'])) { echo "\t\t&lt;div class=\"validationerrorText\"&gt;File upload error occured! Error code: {$_FILES[IMG_FIELD_NAME]['error']}&lt;/div&gt;\n"; }
if (isset($errors['img_nametoolong'])) { echo "\t\t&lt;div class=\"validationerrorText\"&gt;Filename too long! 200 Chars max!&lt;/div&gt;\n"; }
if (isset($errors['img_fileexists'])) { echo "\t\t&lt;div class=\"validationerrorText\"&gt;An image file already exists with that name!&lt;/div&gt;\n"; }
?&gt;
                &lt;br /&gt;&lt;input type="submit" name="submit" id="image1" value="Upload image" /&gt;
        &lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;
&lt;?php

#################################
#
#      F U N C T I O N S
#
#################################

/*
 *  Function: make_thumb
 *
 *  Creates the thumbnail image from the uploaded image
 *  the resize will be done considering the width and
 *  height defined, but without deforming the image
 *
 *  @param   $sourceFile   Path anf filename of source image
 *  @param   $destFile     Path and filename to save thumbnail as
 *  @param   $new_w        the new width to use
 *  @param   $new_h        the new height to use
*/
function make_thumb($sourceFile, $destFile, $new_w=false, $new_h=false)
{
        if ($new_w === false) { $new_w = THUMB_WIDTH; }
        if ($new_h === false) { $new_h = THUMB_HEIGHT; }

        // Get image extension
        $ext = strtolower(getExtension($img_name));

        // Copy source
        switch($ext) {
                case 'jpg':
                case 'jpeg':
                        $img_src = imagecreatefromjpeg($sourceFile);
                        break;
                case 'png':
                        $img_src = imagecreatefrompng($sourceFile);
                        break;
                case 'gif':
                        $img_src = imagecreatefromgif($sourceFile);
                        break;
                default:
                        return false;
        }
        if (!$img_src) { return false; }

        // Get dimmensions of the source image
        $old_x = imageSX($src_img);
        $old_y = imageSY($src_img);

        // Calculate the new dimmensions for the thumbnail image
        // 1. calculate the ratio by dividing the old dimmensions with the new ones
        // 2. if the ratio for the width is higher, the width will remain the one define in WIDTH variable
        //    and the height will be calculated so the image ratio will not change
        // 3. otherwise we will use the height ratio for the image
        //    as a result, only one of the dimmensions will be from the fixed ones
        $ratio1 = $old_x / $new_w;
        $ratio2 = $old_y / $new_h;
        if ($ratio1 &gt; $ratio2) {
                $thumb_w = $new_w;
                $thumb_h = $old_y / $ratio1;
        } else {
                $thumb_h = $new_h;
                $thumb_w = $old_x / $ratio2;
        }

        // Create a new image with the new dimmensions
        $dst_img = ImageCreateTrueColor($thumb_w, $thumb_h);

        // Resize the big image to the new created one
        imagecopyresampled($dst_img, $src_img, 0, 0, 0, 0, $thumb_w, $thumb_h, $old_x, $old_y);

        // Output the created image to the file. Now we will have the thumbnail into the file named by $filename
        switch($ext) {
                case 'jpg':
                case 'jpeg':
                        $result = imagepng($dst_img, $destFile);
                        break;
                case 'png':
                        $result = imagegif($dst_img, $destFile);
                        break;
                case 'gif':
                        $result = imagejpeg($dst_img, $destFile);
                        break;
                default:
                        //should never occur!
        }
        if (!$result) { return false; }

        // Destroy source and destination images
        imagedestroy($dst_img);
        imagedestroy($src_img);

        return true;
}

/*
 *  Function: getExtension
 *
 *  Returns the file extension from a given filename/path
 *
 *  @param   $str   the filename to get the extension from
*/
function getExtension($str)
{
        return pathinfo($filename, PATHINFO_EXTENSION);
}

?&gt;

i still get an error running it on my machine: Warning: mkdir(): No such file or directory in C:\Users\Lyndon\Documents\Web_Dev\ttt.php on line 94

Do you get this on the server with this new code?

Edit: Tiny fix, doesn't fix my problem though

  • 0

hmm, heh well atleast I got more precise errors now... um

Notice: A session had already been started - ignoring session_start() in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/dbc.php on line 55

Change image

array(1) { ["cons_image"]=> array(5) { ["name"]=> string(21) "15jan10jlobscvpiy.jpg" ["type"]=> string(10) "image/jpeg" ["tmp_name"]=> string(37) "/services/webdata/phpupload/php7moGL5" ["error"]=> int(0) ["size"]=> int(51941) } }

Notice: Use of undefined constant __DIR__ - assumed '__DIR__' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload.php on line 75

Notice: Use of undefined constant __DIR__ - assumed '__DIR__' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload.php on line 75

Warning: move_uploaded_file(/uploads/saiyanz2k/images/banner/15jan10jlobscvpiy.jpg) [function.move-uploaded-file]: failed to open stream: No such file or directory in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload.php on line 88

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to move '/services/webdata/phpupload/php7moGL5' to '/uploads/saiyanz2k/images/banner/15jan10jlobscvpiy.jpg' in /services7/webpages/util/s/a/saiya.site.aplus.net/helixagent.com/public/upload.php on line 88

oh wait, with your new code it doesn't show anything, um... think something's not parsing correctly in the PHP

edit: ya check line 90... whats going on there?

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • In the way that you framed it incorrectly. You wrote: "The constant need to close all browser sessions and wait for a new version to install" There's no "constant need to close all browser sessions". That's factually incorrect. The browser downloads its updates in the background and installs them when you open it again. Silently. And there's no "wait for a new version to install", updates are small and take 2-3 extra seconds AT MOST, if any. If you have an SSD, there's zero extra time. Also, every mainstream browser operates this way. Firefox, the FOSS go-to browser, the default on almost every Linux distro, does exactly the same. Also, you don't need to constantly restart Edge for updates to install, you can completely ignore them and it doesn't even ask you to handle them, it's all silent and automatic. So I don't understand what else do you want.
    • DuRoBo Krono Review: Portable E-Ink reader with great ideas that need a bit of improvement by Taras Buria Phone-sized e-readers are gaining traction these days, with more people treating them as a getaway device to cure phone addiction (or at least they are trying to) or having a more pocket-friendly reader that is easier to carry and hold. The market now has plenty of such readers to choose from, and DuRoBo is the latest addition, a new player that offers a more interesting approach to the idea. The Krono is a $279 e-reader with an interesting twist, which tries to make the device more fun and ergonomic. Here is my review. Disclaimer: DuRoBo provided the review sample without any editorial input or pre-approval. The Krono comes in a phone-sized box with pink accents. Inside, you get the device itself, a short user manual, and a USB cable. The cable is a bit old-fashioned, Type-A to Type-C, which is a bit disappointing. Hot take: I would rather have no cable in the box rather than another Type-A cable that gets immediately thrown into my box full of similar cables I never use. The Krono also has no charger in the box, as it relies on accessories you already own, which is fine with me. Here are the specs: Dimensions 154 x 80 x 9.0 mm or 6.06" x 3.15" x 0.35" 173 g or 6.10 oz Materials Black or White plastic Display 6.13-inch E-Ink Carta 1200, 1,648 x 824 pixels, 300 ppi Touch-capacitive. Dual-tone frontlight. Processor 8-core Qualcomm Snapdragon 690 (QTI SM6350) 2 performance cores at 2.07 GHz 4 efficiency cores at 1.71 GHz Memory 6 GB Storage 128GB, non-expandable ~104GB available out-of-the-box Operating system Android 15 with a custom launcher Connectivity Wi-Fi and Bluetooth Battery 3,950 mAh battery Buttons and port USB Type-C port Power button, Volume button, Smart Dial Breathing Lights Audio Mono Speaker and Dual microphones In the box The Krono, a Type-A to Type-C cable, user manual Price $279 on Amazon First impressions Right off the bat, no, this is not a phone replacement. Do not approach this device thinking it can serve you as a dumb phone to cure your TikTok addiction. In addition to the fact that the Krono has no cellular connectivity, I strongly believe that no amount of extra devices can fix your phone addiction until you put some serious effort into it. The Krono is a phone-sized e-reader, a companion for your phone dedicated to reading without distractions. The DuRoBo Krono is made of plastic with a very fine texture. It is hardly premium, but I also cannot say it feels cheap. The device is also a bit thick, quite dense, and well-built without rattling or cracking. You get to choose between two colors: white and black. The front has quite thick bezels, which is hardly surprising for an e-ink device. These things use front light, with LEDs usually placed on the screen perimeter. While I do not mind thicker bezels, the notably larger chin cheapens the look a little. What I mind is a notable seam between the display and the main case, which, after just two days of use, collected plenty of dust and specks. The back of the Krono is what makes the device stand out. There is a cylinder (DuRoBo calls it the Axis) embedded in the back of the reader, housing three elements: a power button on the right edge, a Smart Dial on the left edge, and "Breathing Lights" on the back. An etched DuRoBo logo sits below the cylinder, and it is the only piece of branding you can find on the device. Overall, the design and materials are very unassuming, but the cylinder with additional control elements certainly elevates the look and makes it more interesting. Other physical elements include two microphones (one on the top edge and one on the bottom edge), a USB Type-C port, a volume rocker, and a single mono speaker. There is no fingerprint reader, so if you want to protect your device, a PIN is your only option. The official TPU case is not the most premium-looking Display The Krono has a 6.1-inch E-Ink Carta 1200 touchscreen display with a resolution of 1,648 x 824 pixels (300 ppi). The display is front-lit, and you can adjust the brightness and temperature from cool to warm. Unfortunately, the Krono lacks automatic brightness and temperature adjustments, and you cannot set a custom schedule for the frontlight. However, you can set it to always enable frontlight so that you can see what is happening on the screen when turning it on in a dark environment. On the bright side (get it?), the front light can get extremely dim so that the screen is barely readable in a pitch-dark room. The front light is also uniform across the screen, with no noticeable temperature gradients. I am very susceptible to uneven front light, and it is very easy for me to notice it, but the Krono is doing a very good job in this area. I also like that the edge shadow is not very prominent and barely visible in the black variant. E-Ink Carta 1200 is not the newest generation (there are Carta 1250 and 1300), but it is still a good display. It supports three modes: Clarity, Speed, and Quality. In Clarity mode, text is very sharp and easy to read, but you trade that for more ghosting, a slower refresh rate, and more artifacts when the display changes images. Speed mode, as the name suggests, boosts refresh rate and reduces ghosting, but fine print and text become more jagged. Finally, Quality mode is only available in Android apps. It has the lowest refresh rate, but in return, you get much better visuals, improved gradients, and more. Like brightness and temperature, you can toggle modes from the control center. It is available when swiping from the top-right corner of the screen (the top-left is for notifications). I also like that the Krono can work as a desk clock when not in use. It has a bunch of screensavers, including horizontal clocks with time, date, and current battery level. The screen refreshes once per minute, and battery drain is extremely low (not even 1% in 24 hours). It is a great use of the technology, and another thing I wish more e-ink devices featured. Smart Dial The Smart Dial is Krono's main party trick. It sits on the left side of the device and serves multiple purposes. You can twist or press it to perform various actions, depending on the current use case scenario. When reading books, twisting the dial flips through pages, and pressing it refreshes the screen. On the home screen, the dial adjusts the brightness, and holding the dial pressed launches voice note recording. Finally, a quick double press launches the DuRoBo AI chatbot. While the dial scroll is not notched, it is very smooth and has haptic feedback that confirms your actions, which feels very nice. As a long-term Apple Watch user, I love the idea behind the dial. It feels very natural and oddly satisfying to use, especially with that subtle haptic feedback. I never liked flipping pages with touch input, and I strongly believe each e-reader should come with some sort of physical controls for turning pages. The Krono has both volume buttons (which also work as page turners) and the dial, so you are free to use whichever you prefer. With that said, the dial is not perfect. For one, it sticks out of the case way too far for my liking, raising concerns about durability and longevity when carrying the Krono around in a pocket (it is a pocket-sized device after all). Also, it has too much wobble, which cheapens the experience and makes it feel a bit flimsy and unsecured. While there are two plastic guards on the Krono's case, they are way too small for any kind of protection. I also think DuRoBo should let users customize dial actions (the only available customization is scroll direction), particularly for long and double presses. Not everyone needs voice notes, and DuRoBo AI does not work without an active internet connection, leaving the long press essentially useless when offline. I do not mind these features, and I genuinely think they are useful, but I would rather have the ability to toggle between screen modes, turn the frontlight on/off, or launch my favorite app. I also agree with people on Reddit asking developers to let users adjust the dial sensitivity. I hope this is something DuRoBo can implement with a software update to make the experience more personalized (it is a Smart Dial, after all) and incentivize users to fiddle with the Dial more often. The Dial is a fantastic idea, so please, guys, improve it a little. As for ergonomics, they are mostly fine, but the dial's position may feel a little awkward and way too high. When I use a phone or a phone-sized gadget, I tend to rest one of its corners on my palm for a more secure grip. With the Krono, such a grip is impossible because you cannot reach the dial even with big hands. You have to lower the reader a bit and hold it like a bottle without any extra support for the bottom edge. Such a grip is not necessarily uncomfortable (the Krono is also light enough for it), but it requires a bit of muscle retraining. Sometimes, I do not bother with the dial and hold the Krono like my phone, flipping through pages with volume buttons, as they are perfectly positioned for my right-hand thumb. Interestingly, when testing the Krono, I would often find myself thinking that a roller embedded in the long plastic cylinder on the back of the device would have been a much more comfortable solution. There is a free idea for you, guys. Software The Krono runs Android 15 with a very minimal launcher on top. The home screen presents you with a list of apps, a scrollable list of widgets, and your user profile. Widgets can display time, calendar, or recent books for quick access. You can also add or remove apps from the home screen to keep the most useful stuff around without tapping "Apps." I like this minimalistic approach; it looks clean, easy to understand, and light. I understand that some may find the list of all apps way too clean, but fortunately, DuRoBo lets you switch to traditional icons. The reader also has a bunch of preinstalled apps: Read: The default app for reading. Browser: A Chromium-based browser. Files: A simple file manager. Music: A simple music player. Spark: A voice recorder with transcription support and AI summarization DuRoBo AI: A built-in AI chatbot. Transfer: An app for file transfer over Wi-Fi. If that is not enough, there is the Google Play Store, where you can download all the extra apps you need, alternative readers, podcast apps, chatbots, and more. DuRoBo is not trying to give you an all-in-one device. The standard software experience is quite minimal, which makes it easy to approach and learn. The standard reader supports EPUB, EPUB3, AZW3, MOBI, PDF, TXT, DOC, and DOCX, which is more than enough to let you read most books without third-party software. As for customizing the reading experience, you can select one of five built-in fonts, adjust size and thickness, adjust margins and spacing (only three variants for each), change text alignment and direction, toggle the reading status bar, and switch to dark mode. There is also text-to-speech, which utilizes Android's default TTS tech. While I like the simplistic approach, I cannot help but feel DuRoBo could have made the built-in reader a bit more customizable. However, I am not going to bog down on this, as you can always install any other reader you prefer using the Play Store or by sideloading an APK. Getting books to the Krono is very simple. Given that the device is an Android smartphone without cellular connectivity, you can transfer files via a USB Type-C cable, download them using the built-in browser, share them over Bluetooth, or use cloud storage. My favorite was the built-in Transfer app. It is simple, reliable, and very well-designed. I was surprised by how well-designed the web portal is. It is fast, pretty, and properly categorized. Well done! Once you have your books loaded, you can highlight or underline text, add annotations, bookmark pages, check the table of contents, and ask AI about the selected text. Unfortunately, the Krono has no built-in vocabulary, but again, that is something a third-party reader could fix. Overall, the built-in reader is light and snappy, with just the minimum amount of features for a regular user to enjoy reading books. The Krono has no built-in reading tracking, so stat nerds will have to look for third-party reading apps. However, you can set a daily reading goal, and the reader will notify you when you reach it (for example, one hour). You can also set a reminder to read at a certain time, and when the time comes, the Krono will light up its back LEDs and unlock itself to nudge you. Other than that, the rear LEDs do nothing, not even showing charging progress, which is an unfortunate misopportunity if you ask me. Quirks aside, Krono's Android runs quite snappily and bug-free. Early reviews of the Krono criticized its Android 13-based software quite a lot, but now, the reader runs Android 15, and its software has fixed plenty of initial complaints. I never experienced any issues with built-in apps. AI attempts The DuRoBo Krono comes with a built-in AI chatbot. There is no information on what model powers this thing, but the system says it was "trained by Google." You can launch the bot from the app list or by double-pressing the dial. It works just like any other chatbot, and you can ask it anything by typing or using voice input. The AI saves your chats, and you can rename, export, or delete them. DuRoBo AI requires an active internet connection, and it does not work offline. Its reach and capabilities are also limited. You can only chat in the app and use it in the reader app as a makeshift vocabulary. However, the implementation is kinda awkward. You can only send a selected portion of text to AI without giving it any requests or instructions. I highlighted the word "dumb," and it apologized to me for not being useful. You also cannot ask follow-up questions or send the generated response to a separate chat. The chatbot is also slow, even with fast Wi-Fi, making the overall experience quite frustrating, which makes me again wish for the ability to remap the double press to something else. Spark, the standard voice recording app, also uses AI for note summarization and transcribing. Neither feature works offline, unfortunately. Spark records notes up to 30 minutes using Krono's dual microphones, and you can rename or export notes. Transcription quality is decent, and the speed is alright, but you can find much better solutions in the Google Play Store. What I like about Spark is that transcribed notes are not locked, and you can always type more to elaborate on your ideas, which is handy. Overall, I like that the Krono is not shoving AI down my throat, but to be honest, there is really not that much to shove. AI features here feel raw and need improvements to be more useful. Battery Life Like most E-Ink readers, the Krono has fantastic battery life. Even with a clock as a screensaver, its standby power consumption is incredibly low. And when in use, you can get weeks of reading on a single charge. Without the front light, my unit never sipped more than one or two percent of battery during a one-hour reading session. It was nice to see plenty of battery-related settings. You can limit charging at 80% to protect battery health long-term, check the number of charging cycles, manufacturing/first-time use date, battery health, and the maximum capacity. Additionally, the Krono lets you select what hardware remains enabled when sleeping. This lets you keep Wi-Fi and Bluetooth on (say, if you want to receive notifications, for some reason) and keep audio playing when locked. Turning these features off effectively eliminates any standby battery drain. I left my Krono sitting for 24 hours with a clock screensaver on, and it did not drop a single percent. The pretty big 3,950 mAh battery justifies the device's thickness and ensures you do not have to charge it for long periods. Speaking of charging, it is capped at only 10W, which is a bit disappointing, as getting such a big battery to 100% takes a notably long time in the era of super-fast charging smartphones. DuRoBo Moodi The Moodi is a standalone, optional accessory for your Krono. It is a wireless remote with two customizable buttons that you can use to flip pages, control media, or scroll webpages. The accessory connects via Bluetooth. Despite having a built-in rechargeable battery, it is extremely light. While the Moodi's shape and form factor is not what I would call particularly ergonomic, it is not uncomfortable to hold and use. The Moodi comes with six removable magnetic buttons with various smiley faces. Buttons sit securely, and they have nice-feeling, albeit a little loud, clicks. It is a cute touch that adds a little more fun and character to the device. There is also an accented power button and a single status LED. The latter displays charging status and connection mode. The Moodi supports three modes: Reading: Buttons work as volume buttons, allowing you to flip pages in the built-in reader or other apps that support page turning with volume buttons. Media: Buttons work as skip forward/backward, which is useful when listening to audiobooks, podcasts, or music. Scroll: The third mode lets you scroll pages in the web browser or any other application The Krono properly detects the Moodi and presents you with an on-screen guide when you connect it for the first time (it also displays the battery level). However, you can only change modes by holding both buttons for a few seconds. It is also worth noting that the Moodi works with other devices. I connected it to my iPhone and it let me adjust volume or control media playback. Sadly, the scroll did not work, so you cannot use it to waste time scrolling TikToks. Overall, the Moodi is a cute little accessory, which I can recommend for those who read a lot. It is very useful for remote page flipping when you do not want to burden your hands by holding the Krono all the time. I only wish DuRoBo included a lanyard for the built-in loop. As for the battery life, after using the Moodi for a few days, I only managed to drop several percent of its 90 mAh battery. Despite the small size, it is rated for weeks of use, which is pretty impressive. At $35.99, I cannot say the Moodi is a must-have accessory, but I see the appeal. I prefer using the Krono with its Smart Dial, as I rarely read for more than 40-60 minutes in one sitting. However, if you have a stand and like reading for long periods, the Moodi is the right thing to have. It is a bit more expensive than regular page flippers on Amazon, but it is on par with similar products from Kobo or BOOX. Plus, it has a little more fun to it with removable buttons and better integration into the Krono. Conclusion At the end of the day, DuRoBo Krono is a nice pocket-sized e-reader. Its software focuses on the main things without trying to be everything at once. The smart dial idea is unique and great, and I wish more manufacturers had something similar in their devices. The display is also good, with an even frontlight and "always-on" support. I did not notice any deal-breaking issues with the Krono. However, you can feel that the idea needs some improvements, such as a slightly stiffer dial in a more ergonomic location, perhaps a little more premium materials, and better software customization. I hope the company won't give up on the idea and improve the dial and ergonomics in the second generation. Buy DuRoBo Krono Black - $279.99 on Amazon Buy DuRoBo Krono White - $279.99 on Amazon Buy DuRoBo Moodi - $35.99 on Amazon As an Amazon Associate, we earn from qualifying purchases.
    • In what way is any of what I said incorrect? To install an update you need to close all browser instances, upping it from once a month to once a fortnight is an inconvenience for users. Particularly when updates don't offer functionality that users want (notably copilot). Security updates should come as they are needed, not on a release schedule
    • Dopamine 3.0.6 by Razvan Serea Dopamine is an awesome free audio player which tries to make organizing and listening to music as simple and pretty as possible. Dopamine has been designed for Windows 7, Windows 8.x and Windows 10 and plays mp3, ogg vorbis, flac, wma and m4a/aac music formats quite well. The best part? It's created by long-time Neowin member, Raphaël Godart. If you’re looking for a music player to handle a large music collection, you should definitely give Dopamine a try. Dopamine 3.0.6 changelog: Fixed Manually edited album covers are overwritten on the next collection refresh Fixed AppImage package not working on modern GNU/Linux distributions Deleting song from playlist sometimes fails Playback controls only work when clicking on upper half of the buttons It's unclear that files must be tagged with an external ReplayGain scanner (for example rsgain) before normalization can take effect. Change to Artist or Album tags is not reflected in the song list view nor in the Now Playing information ReplayGain issues Smart playlist filters ignore text containing accents or other special characters Some MP3 files trigger an "MPEG header not found" error due to a too-narrow initial MPEG header scan range Changed Updated the Vietnamese translation Download: Dopamine 3.0.6 | 122.0 MB (Open Source) Links: Home Page | Forum Discussion | Screenshot | Other OSes Get alerted to all of our Software updates on Twitter at @NeowinSoftware
  • Recent Achievements

    • One Month Later
      AndreaB earned a badge
      One Month Later
    • One Month Later
      agatameier earned a badge
      One Month Later
    • Week One Done
      agatameier earned a badge
      Week One Done
    • Week One Done
      ssd21345 earned a badge
      Week One Done
    • Contributor
      MarkHughes4096 went up a rank
      Contributor
  • Popular Contributors

    1. 1
      +primortal
      518
    2. 2
      +Edouard
      195
    3. 3
      PsYcHoKiLLa
      147
    4. 4
      ATLien_0
      96
    5. 5
      Steven P.
      76
  • Tell a friend

    Love Neowin? Tell a friend!