• 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

    • Well I really think the repasting helped if your higher clocks have returned, maybe the next thing to look at is if there is a problem with your case airflow? I guess this because your 3080 has returned to optimal state, but is still staying too warm, which might suggest it was thermal throttling before you repasted, of which the only logical conclusion could be outside factors.
    • Samsung Galaxy Z Fold 8, Flip 8, Z Fold Wide: Everything you need to know by Hamid Ganji Galaxy Z Fold 7 - Image via Samsung The next generation of Samsung foldables is set to be unveiled next month at the second Unpacked event of the year. Samsung’s 2026 foldables are not expected to offer significant upgrades over their predecessors, with the Korean firm instead focusing on design refinements and conventional upgrades such as faster processors and better cameras. However, Samsung is reportedly planning to unveil an all-new passport-style foldable this year to rival Apple’s first foldable iPhone, which is expected to debut this September. Here’s a roundup of everything we know about Samsung’s upcoming foldable devices ahead of their official debut. When can we expect Samsung’s new foldables? The Galaxy Z Fold 7 and Z Flip 7 series were unveiled in July, and Samsung is expected to maintain this timeframe in 2026. Based on previous reports from Korean sources, Samsung will hold its Unpacked event on July 22 in London, UK, to pull back the curtain on the Galaxy Z Fold 8 series. The devices are also expected to hit the shelves a few weeks after launch. However, Samsung has yet to announce an official date. A new naming scheme? One of the most interesting changes we might see this year is a new naming scheme for Samsung’s latest foldables. SamMobile reported that since Samsung is expected to unveil three foldables this year, it has adopted a new naming strategy to simplify product identification for customers. Accordingly, the standard Galaxy Z Fold 8 will reportedly be called the Galaxy Z Fold 8 Ultra and will serve as the direct successor to last year’s Galaxy Z Fold 7. The “Ultra” suffix suggests the phone could feature higher-end specifications, such as additional rear camera modules. Samsung’s new passport-style foldable is expected to carry the Galaxy Z Fold 8 name without any suffix. This model is reportedly equipped with two rear cameras. No major changes are expected for the Flip model. Galaxy Z Fold 8 Ultra and Z Flip 8 anticipated specs Rumors over the past few months suggest Samsung is preparing several upgrades for its upcoming foldables, although the devices may continue to rely on larger batteries and faster charging speeds rather than dramatic design changes. The primary focus this year is expected to be the Galaxy Z Fold 8 and its wide-screen design. Galaxy Z Fold 8 Ultra official CAD renders - Image via AndroidHeadlines Here are the anticipated specifications for the Galaxy Z Fold 8 Ultra based on previous leaks: 6.5-inch outer display and 8-inch inner display, 120Hz refresh rate, and 2,600 nits peak brightness Snapdragon 8 Elite Gen 5 processor, paired with 12GB or 16GB of RAM and 256GB, 512GB, or 1TB of storage 4.1mm thickness when unfolded and a weight of 210g 200MP main camera, 50MP ultrawide camera, 10MP or 12MP telephoto camera, 10MP cover camera, and 10MP selfie camera 5,000mAh battery with 45W wired charging Android 17 and One UI 9 As for the Galaxy Z Flip 8, the device is not expected to be a major departure from its predecessor, although it could become slightly slimmer. Expected specifications include: Snapdragon 8 Elite Gen 5 or Exynos 2600 processor 12GB of RAM with 256GB and 512GB storage options 6.9-inch Dynamic AMOLED 2X inner dispaly and 4.1-inch Super AMOLED outer dispaly 50MP main camera, 12MP ultrawide camera, and 10MP selfie camera 4,300mAh battery with 25W wired charging Android 17 and One UI 9 Samsung’s foldables are also expected to launch with Gemini Intelligence, Google’s AI suite for automating tasks in Android ecosystem. Moreover, given current memory and component costs, some Galaxy Z Fold 8 Ultra and Z Flip 8 variants could see a price hike. Galaxy Z Fold 8 adopts a wide-screen design The centerpiece of the upcoming Unpacked event could be the Galaxy Z Fold 8, previously rumored as the Galaxy Z Fold Wide. This model adopts a passport-style form factor and is expected to compete directly with Apple’s iPhone Fold. Galaxy Z Fold 8 official CAD renders - Image via AndroidHeadlines Here’s what to expect: 7.6-inch primary OLED display and 5.4-inch cover display, 120Hz refresh rate, 2,600 nits peak brightness, and 4:3 aspect ratio Snapdragon 8 Elite Gen 5 processor, 12GB or 16GB of RAM, and 256GB, 512GB, or 1TB storage options 4,800mAh battery with 45W wired charging 50MP main camera, 50MP ultrawide camera, and 10MP selfie camera Android 17 and One UI 9 The three new foldable phones are unlikely to be the only devices unveiled at Samsung’s Unpacked event. The company is also expected to introduce the Galaxy Watch Ultra 2 and the Galaxy Watch 9 series.
    • Thanks
    • 7 Days: Killing uBlock Origin bypasses, Euro Office faces fire, and will AI replace you? by Aditya Tiwari 7 Days is a weekly roundup of picks of what's been happening in the world of technology - written with a dash of humor, a hint of exasperation, and an endless supply of (black) coffee. This week's highlights include WWDC 2026 announcements, updates on child safety, and Meta's use of data from outside businesses to optimize your feed. Let's get started. You can check out the recent issues of the 7 Days weekly roundup. Killing uBlock Origin bypasses The hottest news of the week was about Google Chrome effectively ending most uBlock Origin workarounds (a free, open-source ad blocker extension) by permanently dropping MV2 extensions and their bypasses. Chrome is transitioning towards newer MV3 extensions. A recent discussion thread highlighted how the latest and upcoming versions of the most popular browser are expected to be its final releases with support for MV2 extensions. Genuinely European? Euro-Office faces fire The recently launched cloud-based office suite, Euro-Office, is facing criticism at home. The LibreOffice developer wrote an open letter criticizing Euro-Office for its marketing claim that it's the "first open-source office suite developed in Europe," since the honor has belonged to OpenOffice since 2001. The Document Foundation has called out Euro-Office, arguing that it can't consider "itself genuinely European" as long as it keeps pushing Microsoft defaults on users, adding that "it has to speak ODF as its mother tongue." Will AI replace you? Image: Tara Winstead via Pexels Microsoft's AI boss, Mustafa Suleyman, said in an interview earlier this year that AI would replace office workers within 12 to 18 months. Joining the ranks of top executives who have softened their stance on AI replacing humans, Suleyman recently walked back his earlier remarks and now says that AI will automate tasks, not replace entire white-collar jobs. He defended his earlier comments by arguing that they referred only to individual actions people perform at their desks. Louis Rossmann wants to sue Samsung Image: Louis Rossmann Tech repair entrepreneur and right-to-repair activist Louis Rossmann contacted Samsung support over a failed 4TB Samsung 990 Pro NVMe SSD. After back-and-forth communication, Samsung offered a $330 refund instead of a replacement, but Rossmann found that the SSD was readily available for new buyers at a higher price. He has issued a formal 60-day notice and intends to file a suit in Texas small claims court, as Samsung's actions reflect a failure to honor its warranty obligations. Samsung reached out to Neowin to clarify its updated stance that customers in such situations will receive a refund equal to the product's current market price. Child safety or mass surveillance? Image: Jonathan Borba via Pexels Signal accused the UK government of using child safety and device-level explicit content ban as a cover for mass surveillance. Calling the plan "dystopian," Signal warned that it violates everyone's fundamental right to privacy. The messaging platform believes that the government should keep children "safe" and "protected," but it should do so through social services and education. Fears of social media regulation Image via DepositPhotos.com More governments across the globe are tightening their grip on social media and bringing stricter regulations in the name of child safety. Bluesky COO, Rose Wang, warned that social media regulations could destroy competition from small startups and that heavy regulatory compliance costs favor deep-pocketed tech giants while locking out new entrants. Our Features Image: Pexels Our coffee-powered team publishes a platter of editorials, opinion posts, and guides. Here's what they got for the week: UK **** blockers are a looming privacy disaster, we must be able to see the source code This week in software news Image: Proton Catch up on some of the latest software news updates that arrived throughout the week: Dark clouds over PC makers: Building on our report from last month, Dell officially acknowledged that its own remediation software was causing BSOD issues and unexpected system restarts. HP is also facing equally frustrating issues involving recent Windows Secure Boot updates on Windows 11. Controversial icon: Spotify finally removed the disco ball icon from its app and replaced it with the familiar flat green logo after weeks of mixed reactions online. While some people don't like the new design, the retro, three-dimensional look has generated a following of its own. Even other brands are coming up with their versions of the disco logo. NVIDIA fixes stuff: A new hotfix driver 610.52 fixes various issues related to monitors and displays, noting that G-SYNC-related frame pacing troubles should now be resolved on Ada Lovelace GPUs. The feedback thread also points out that the hotfix patches a BSOD issue. FIFA World Cup tracker: Opera is redesigning its Android browser with a built-in football tracker for the upcoming World Cup in the US. The new homepage is now "more immersive" with easier access to common browser features. Command line for Proton: The Swiss technology company has launched a command line version of the Proton Drive, which you can use to manage your encrypted files directly from a terminal across all major platforms, including Windows, macOS, and Linux. This week in hardware news Image: Thermaltake Catch up on some of the latest software news updates that arrived throughout the week: Intel and AMD PCs in one case: Thermaltake's CAPO X dual-system chassis brings you the best of both worlds by supporting two microATX (mATX) motherboards and up to two 360 mm AIO liquid coolers. If you want ideas, maybe you can use one as your main PC and another as an AI agent. Google Tensor production: While TSMC will remain the lead producer, the search giant is reportedly in talks with Samsung to hand over part of the production of its next-generation Tensor AI chips. The upcoming TPUs are reportedly codenamed “Icefish” and will be produced using Samsung's 2-nanometer process technology. Lethal fake phone chargers: UK-based consumer rights organization Which? has warned that "potentially lethal knock-off chargers" are still being sold on online marketplaces, including Amazon and eBay, despite the dangers of such chargers having been exposed. This week in Google News Image: Google Catch up on some of the latest Google news updates that arrived throughout the week: Sliding into DMs: You might remember that YouTube had a direct messaging feature back in the day. It's now rolling out a revamped direct messaging inbox that lets you share Shorts, videos, and live streams and have conversations about them. New in NotebookLM: The AI-powered note-taking app got some new agentic capabilities and more advanced reasoning, thanks to support for Gemini 3.5 and Antigravity. NotebookLM can now generate outputs in more formats, making it easier to start new projects with less information. This week in Apple News Image: Apple Catch up on some of the latest Apple news updates that arrived throughout the week: WWDC 2026: This week was all about Apple's annual developer conference, where the iPhone-maker finally unveiled an upgraded Siri AI and a platter of new Apple Intelligence features. Siri AI now has a cross-platform app, which is supported on select models of iPhone, iPad, Mac, Apple Watch, and Vision Pro. What's different about WWDC: I wrote a detailed feature this week discussing how Apple changed the WWDC keynote this year, blurring the lines between its operating systems. Apple didn't have dedicated segments for its operating systems this year and didn't even publish the official press releases. Liquid Glass slider (finally): It's that time of the year when Apple previews fresh updates for iPhone, iPad, Mac, Apple Watch, AirPods, and other platforms. A new transparency slider for Liquid Glass is coming to iOS 27, iPadOS 27, and macOS 27 Golden Gate. Is your device supported?: If you're wondering whether your Apple device supports the new developer beta builds, you can check the respective compatibility lists for iOS 27, iPadOS 27, macOS 27, and watchOS 27. Siri AI not coming to Europe: Yes, that's true due to complications related to the Digital Markets Act (DMA). While Apple penned a blog post to tell its side of the story, a European Commission spokesperson told Neowin that the DMA does not prohibit Apple from launching its services in the EU; the company is simply required to comply with the law. New child safety features: Apple announced a trove of new safety features for kids, including a simpler setup experience for parents, Ask to Browse, Time Allowances, and a redesigned Screen Time UI. Parents can now visit a new website to find answers to common questions around child safety features. More cloud power: Apple's Private Cloud Compute cloud infrastructure will now run beyond its own data centers for the first time. It's working with Google and NVIDIA to run new Apple Intelligence workloads on Google Cloud systems powered by NVIDIA GPUs. This week in Meta news Catch up on the latest Meta news updates that arrived throughout the week: Data from outside: Meta is rolling out a new update globally to personalize your AI responses and primary feeds using data from outside businesses. It already targets ads based on shopping activity, but the latest development enables it to personalize other "parts of your experience." There is a toggle in the Settings to disable activity from other businesses; however, it won't prevent companies from sending your data to Meta. Level playing field: The European Commission has ordered the social media giant to restore access to WhatsApp for third-party AI chatbots, including ChatGPT and Copilot. Meta previously blocked rival AI chatbots from operating on WhatsApp, prompting the Commission to launch an antitrust investigation. Spying on users: On the flip side, WhatsApp accused the Israeli cyber-intelligence firm, NSO Group, of deploying a fresh wave of targeted "spear phishing" attacks against its users, which were thwarted by WhatsApp's security teams. Reorder profile grid: Adding some customization for the profile grid feature, Instagram now lets you rearrange posts in your profile without deleting and reuploading content. Go to your profile and long-press any thumbnail to find the "Reorder grid" option. This week in AI news Catch up on the latest artificial intelligence news updates that arrived throughout the week: Claude RAM hogger: Windows users are getting infuriated by Claude Desktop's hidden 1.8GB Hyper-V VM bug, which spins up if you use Claude Cowork or agent mode even once. It shows a Vmmem process in Task Manager, indicating 0% CPU usage but 1.8GB of RAM usage. Claude Fable 5: The new state-of-the-art AI model from Anthropic beats OpenAI's ChatGPT-5.5 in multiple AI benchmarks. Claude Fable 5 sits above the Opus models and outperforms most other generally available models across knowledge work, vision, scientific research, and more. However, the model was abruptly suspended after receiving an export control directive from the US government. Stack Overflow for AI agents: The popular Q&A platform has launched Stack Overflow for Agents in beta, which AI agents can use to share, find, and reuse coding knowledge. It explained that AI agents operate in isolation, creating an Ephemeral Intelligence Gap, and valuable tokens are wasted on something another agent has already solved. Upgrading Codex: OpenAI is buying a company called Ona, which makes secure cloud execution and orchestration technology for developers. The ChatGPT-maker aims to make Codex agents run for days without being tied to a local machine or an active session. It also announced a new developer mode in Chrome. This week in open-source news Catch up on some of the latest open-source and Linux updates that arrived throughout the week: Linux 7.1 rc7: Linux Torvalds dropped an optimized rc7 with crucial fixes for AMD and laptop hardware. He said that a stable version of Linux 7.1 could arrive next week, adding that the latest RC is not small, but smaller than recent releases. Alpine Linux 3.24: The latest Alpine Linux release added support for COSMIC Desktop, Linux 6.18, IPv6 installer support, automatic serial console configuration for headless setups, and major package updates and removals. This week in Microsoft News Microsoft had to shut down more than 70 GitHub repos after they were compromised by malware, Teams is getting a controversial tracking feature that users may hate, and the company explained why the new update makes PowerToys faster. You can check out Taras's freshly baked Microsoft Weekly roundup to catch up on all the interesting stories this week. This week in gaming The latest issue of Pulasthi's Weekend PC Game Deals curates several exciting games on sale this week. On the Epic Games Store, the new titles on display for grabs include Warhammer 40K Speed Freeks and The Ouroboros King. NVIDIA GeForce NOW's summer sale lowered the prices of both the Performance and Ultimate membership options for a limited time period. Meanwhile, the Xbox Free Play Days brought Undead Labs' post-apocalyptic title State of Decay 2, as well as two Team17-published titles. That said, here are some more stories from the gaming world: Dragon's Dogma 2: Dark Arisen expansion to bring snowy region, new updates also coming Playground drops 30 minutes of Fable gameplay, shows off life sim and morality system Playground Games confirms Forza Horizon 6 save wipe bug Doom: The Dark Ages Revelations expansion gives the Slayer a brutal Chain Spear State of Decay 3 is out in 2027, reveals Plague Nests with new co-op gameplay trailer From the review corner This week, Taras got his hands on the DuRoBo Krono portable e-ink reader, which comes with a $279 price tag. It's a smartphone-sized device with a rotating dial, sitting somewhere between premium and cheap in terms of build quality. Speaking of the pros, the physical controls are cool, the smart dial is useful, the battery life is good, and Android 15 has no-nonsense software. On the flip side, the device lacks software customization, the built-in AI needs improvement, the smart dial is a bit wobbly, and there is no ambient light sensor. EA Sports UFC 6 EA Sports UFC 6 does a better job at onboarding new players than most fighting games, according to Pulasthi's detailed review. The game comes with rewarding combat systems, top-notch animation, impressive impact physics, and visible damage on fighters. However, the menus lag a lot, grappling isn't very fun, and the flow state feels a little misplaced. More price drops! We got you covered with some hot tech deals all week. For some reason, if you missed out on a great discount, here is a summary of some recent deals that are still alive: GIGABYTE Radeon RX 9070 XT Gaming OC ICE 16G - $649.99 (13% off) 1TB Samsung T7 Portable SSD - $189.98 (31% off) AirPods Pro 3 - $179 ($50 off) Edifier R1280Ts Powered Bookshelf Speakers - $129.99 (24% off) To view all of our recent deals, click here. So, these were some of the biggest tech news and other updates from this week. There will be more issues of our 7 Days series in the coming weeks and months, so stay tuned. You can also support Neowin by registering for a free member account or subscribing to extra member benefits, along with an ad-free tier option. Have a great weekend!
  • Recent Achievements

    • Week One Done
      rolfus earned a badge
      Week One Done
    • One Month Later
      Leroy Jethro Gibbs earned a badge
      One Month Later
    • Conversation Starter
      flexorcist earned a badge
      Conversation Starter
    • One Month Later
      AndreaB earned a badge
      One Month Later
    • One Month Later
      agatameier earned a badge
      One Month Later
  • Popular Contributors

    1. 1
      +primortal
      505
    2. 2
      +Edouard
      196
    3. 3
      PsYcHoKiLLa
      141
    4. 4
      ATLien_0
      90
    5. 5
      Steven P.
      81
  • Tell a friend

    Love Neowin? Tell a friend!