PHP image replacement? - php

I'm having a brain dead moment... If someone could talk this through with me and make suggestions that'd be great.
I'm importing a URL from a database, eg www.mysite.com/images/image1.jpg set as variable newimage1
This is loaded from the DB and placed on the page.
As this is an edit page, the user can upload a new image.
If the user doesn't upload a new image, but saves the page anyway, the variable newimage1 is not set, it clears the existing image url from the database because the variable is set to "".
What's the best way to do this? An if statement, that checks if newimage1 is blank and removes it from the update to the database?
Sorry for this simple question!

$image_name = "";
if(!empty($_FILES)){
$image_name = $_FILES['image']['tmp_name'];
}
$sql = "UPDATE table SET var1 = 'value1', var2='value2'";
if($image_name != "")
$sql .= ", image_name = '".$image_name."'";
$sql .= " WHERE id_entry = 5";

if( empty($_REQUEST['newImage1']) ) {
//program logic
} else {
//program logic
}

Related

error to upload to images with php

I am trying to upload two images with php. And add them to the database. Somehow it only uploads one image and the records in the database always have the same values.
this is the code i use
<?php
include "../connect.php";
$name1 = $_FILES['pic1']['name'];
$size1 = $_FILES['pic1']['size'];
$name2 = $_FILES['pic2']['name'];
$size3 = $_FILES['pic2']['size'];
if(isset($_POST['name']))
{
$extension1 = pathinfo($name1,PATHINFO_EXTENSION);
$array = array('png','gif','jpeg','jpg');
if (!in_array($extension1,$array)){
echo "<div class='faild'>".$array[0]."-".$array[1]."-".$array[2]."-".$array[3]." --> (".$name.")</div>";
}else if ($size>10000000){
echo "<div class='faild'>Size</div>";
}else {
$new_image1 = time().'.'.$extension1;
$file1 = "images/upload";
$pic1 = "$file1/".$new_image1;
move_uploaded_file($_FILES["pic1"]["tmp_name"],"../".$pic1."");
$insert = mysql_query("update temp set pic='$pic1' ") or die("error ins");
}
$extension2 = pathinfo($name2,PATHINFO_EXTENSION);
$array = array('png','gif','jpeg','jpg');
if (!in_array($extension2,$array)){
echo "<div class='faild'>".$array[0]."-".$array[1]."-".$array[2]."-".$array[3]." --> (".$name.")</div>";
}else if ($size>10000000){
echo "<div class='faild'>Size</div>";
}else {
$new_image2 = time().'.'.$extension2;
$file2 = "images/upload";
$pic2 = "$file2/".$new_image2;
move_uploaded_file($_FILES["pic2"]["tmp_name"],"../".$pic2."");
$insert = mysql_query("update temp set passport='$pic2'") or die("error ins");
}
}
?>
One of the problems you have is with your update statement. There is no 'where' statement saying which record in the database should be updated so this query updates them all. That's why you only have the last image in all the database rows.
Besides that, your code is not very good from a security point of view. You should take a look at mysqli or pdo for your database connection and queries because MySQL is deprecated and removed from PHP. Also take a look at SQL injections and data validation. Besides some very basic extension and size validation there is nothing there to keep things save. Try escaping and validating all user inputs.
And another point would be to take a look at 'functions'. You're running almost the exact same piece of code at least twice. And every code change has to be done twice. Perfect for a function call, something like
function storeImage($image){
// write the uploading and storing PHP here
}

PHP: define name for file upload

I have a peace of code that stores profile images in the map "images/profiles" and stores the URL in the database. I want to define the name of the uploaded profile picture to be the $ID of the user. How can I do this?
include("../../core/init.inc.php");
$target = "../images/profiles/";
$target = $target . basename($_FILES['photo']['name']);
$pic = $_FILES['photo']['name'];
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) {
echo "The file ". basename($_FILES['photo']['name']). " has been uploaded";
} else {
echo "ERROR";
}
mysql_query("UPDATE users SET image_url='includes/images/profiles/$pic' WHERE username = '".mysql_real_escape_string($_SESSION['username'])."'");
Now when someone uploads his profile picture (lets call it pf1.png) it saves it as "pf1.png". I want it to be saved like "$ID.png" (.png being a random extension). I want to accomplish this both for the move_upload_file function and updating the 'image_url' database column correctly.
According to the example in the documentation you can provide the filename in the destination of move_uploaded_file(). If that fails you can simply rename() the file after saving it.
try changing
$target = $target . basename($_FILES['photo']['name']);
to:
$filename=$_FILES["file"]["tmp_name"];
$extension=end(explode(".", $filename));
$target = target . $_SESSION["ID"].".".$extension;
side note: You are not escaping $pic this makes your site vulnerable to sql-injection
I don't know how you saved the ID of the user, but to make it easy let's assume you stored the ID in a session.
Then simply change the $target.
$target = $target . $_SESSION['ID'];
Also change your query as follows:
$url = "includes/images/profiles/" . $_SESSION['ID'];
SET image_url="$url"
Note: I don't know why you got an image folder inside an includes folder, but I guess you made that choice for yourself.
you can get the last inserted id and make it as a name of your image/uploaded file
$qry = mysqli_query($dbconnection,"INSERT INTO statements here");
$last_id = mysqli_insert_id($dbconnection);
//$ext= you get the extension of the file uploaded
move_uploaded_file($tmpname,$target.$last_id.$ext);
now if you want it to be accomplished in updating also.
you can always get the ID of the data you want to fetch and make it as a basis in updating.
ex.
$id = $_GET['id'] || $id = $row['id']; //anything depends on how you want it to retrieve
then you can do the query and move_uploaded_file function
$qry = mysqli_query($dbconnection,"UPDATE tblname SET field='$anything' WHERE id = '$id'");
move_uploaded_file($tmpname,$target.$id.$ext);
of course $tmpname will be the basis on what file you have uploaded, $tmpname will be the file you want to move into your desired directory

How to use a variable in 2 different Php files?

I have am creating a Website that showes Visitors Info. Users are able to visit the page and use Textarea to pick a name for their URL, and the name will be saved as a table in mysql database..
I am using the $name variable in my first php file which is a replacement for the text "visitor_tracking". But today I noticed that there is also another php file and more sql codes, and once again I can see that this file also has the "visitor_tracking" text used in the sql code.
But I think I failed big time, because I simply dont know how to replace the "visitor_tracking" text with my the variable name called $name.
<?php
//define our "maximum idle period" to be 30 minutes
$mins = 30;
//set the time limit before a session expires
ini_set ("session.gc_maxlifetime", $mins * 60);
session_start();
$ip_address = $_SERVER["REMOTE_ADDR"];
$page_name = $_SERVER["SCRIPT_NAME"];
$query_string = $_SERVER["QUERY_STRING"];
$current_page = $page_name."?".$query_string;
//connect to the database using your database settings
include("db_connect.php");
if(isset($_SESSION["tracking"])){
//update the visitor log in the database, based on the current visitor
//id held in $_SESSION["visitor_id"]
$visitor_id = isset($_SESSION["visitor_id"])?$_SESSION["visitor_id"]:0;
if($_SESSION["current_page"] != $current_page)
{
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string, visitor_id)
VALUES ('$ip_address', '$page_name', '$query_string', '$visitor_id')";
if(!mysql_query($sql)){
echo "Failed to update visitor log";
}
$_SESSION["current_page"] = $current_page;
}
} else {
//set a session variable so we know that this visitor is being tracked
//insert a new row into the database for this person
$sql = "INSERT INTO visitor_tracking
(ip_address, page_name, query_string)
VALUES ('$ip_address', '$page_name', '$query_string')";
if(!mysql_query($sql)){
echo "Failed to add new visitor into tracking log";
$_SESSION["tracking"] = false;
} else {
//find the next available visitor_id for the database
//to assign to this person
$_SESSION["tracking"] = true;
$entry_id = mysql_insert_id();
$lowest_sql = mysql_query("SELECT MAX(visitor_id) as next FROM visitor_tracking");
$lowest_row = mysql_fetch_array($lowest_sql);
$lowest = $lowest_row["next"];
if(!isset($lowest))
$lowest = 1;
else
$lowest++;
//update the visitor entry with the new visitor id
//Note, that we do it in this way to prevent a "race condition"
mysql_query("UPDATE visitor_tracking SET visitor_id = '$lowest' WHERE entry_id = '$entry_id'");
//place the current visitor_id into the session so we can use it on
//subsequent visits to track this person
$_SESSION["visitor_id"] = $lowest;
//save the current page to session so we don't track if someone just refreshes the page
$_SESSION["current_page"] = $current_page;
}
}
Here is a very short part of the script:
I really hope I can get some help to replace the "visitor_tracking" text with the Variable $name...I tried to replace the text with '$name' and used also different qoutes, but didnt work for me...
And this is the call that I used in my 2nd php file that reads from my first php file:
include 'myfile1.php';
echo $var;
But dont know if thats correct too. I cant wait to hear what I am doing wrong.
Thank you very much in advance
PS Many thanks to Prix for helping me with the first php file!
first you need to start session in both pages. it should be the first thing you do in page before writing anything to page output buffer.
In first page you need to assign the value to a session variable. if you don't start session with session_start you don't have a session and value in $_SESSION will not be available.
<?php
session_start(); // first thing in page
?>
<form action="" method="post" >
...
<td><input type="text" name="gname" id="text" value=""></td>
...
</form>
<?PHP
if (isset($_POST['submit'])) {
$name = $_POST['gname'];
//...
//Connect to database and create table
//...
$_SESSION['gname'] = $name;
...
// REMOVE THIS Duplicate -> mysql_query($sql,$conn);
}
?>
in second page again you need to start session first. Before reading a $_SESSION variable you need to check if it has a value (avoid errors or warnings). next read the value and do whatever you want to do with it.
<?php
session_start(); // first thing in page
...
if(isset($_SESSION['gname'])){
// Read the variable from session
$SomeVar = $_SESSION['gname'];
// Do whatever you want with this value
}
?>
By the way,
In your second page, I couldn't find the variable $name.
The way you are creating your table has serious security issue and least of your problems will be a bad table name which cannot be created. read about SQL injection if you are interested to know why.
in your first page you are running $SQL command twice and it will try to create table again which will fail.
Your if statement is finishing before creating table. What if the form wasn't submitted or it $_POST['gname'] was emptY?
there are so many errors in your second page too.

Proper Way To Display A Default Image When Replacement Image Is Missing in PHP

I have the following code that is used to load user images from a database when their information is displayed.
I was attempting to write it in a way in which it would check if the user already has an image tied to their user id in the database and if so, would leave the image alone and if not, would display a "missing.jpg"/default user image.
I've tried the following, but right now it seems the code is overwriting existing images and replacing them with the missing.jpg image and I don't know why.
I'd appreciate somebody taking a look and showing me why that is.
//Images
$thisScript = $_SERVER["SCRIPT_FILENAME"];
$dirName = dirname($thisScript);
$relative_path = "images/headshots/".$this->id.".jpg";
$missing_path = "images/headshots/missing.jpg";
$full_path = $dirName . "/" . $relative_path;
//if(file_exists($relative_path))
//if(file_exists($_FILES['uploadedfile']['name']))
if(basename( $_FILES['uploadedfile']['name']) != '' /*and (file_exists($_FILES['uploadedfile']['name']))*/)
{
$this->process_headshot_file($relative_path, $full_path);
}
else
{
//$this->process_headshot_file($missing_path, $full_path);
$query = "UPDATE hraps SET headshot_filename = '".$_SESSION['missing_headshot_image']."' WHERE id = ".$this->id;
$result = mydb::cxn()->query($query);
}
Thank you in advance for your help.
Your if statement here:
if(basename( $_FILES['uploadedfile']['name']) != '')
is only going to work when there's something in $_FILES
Since you say you want to display an image when their information is displayed, that's probably not going to trigger very often, so the else is going off instead.
I don't think you need to do anything more complicated than this:
$image = "images/headshots/missing.jpg";
if(file_exists($relative_path)) {
$image = $relative_path;
}
$full_path = $dirName . "/" . $image;
$this->process_headshot_file($image, $full_path);

MySQL Updating some database fields without overwriting fields not changed

Ok, this one is driving me nuts. I have a backend file uploader that uploads .jpg files to the server. Then I want to upload the filename(s) of the .jpgs to my database. So when the page loads I can add the filename from the database and the pictures will display on the page. This works fine, but I also need to be able to update the files and the filenames in the database. If the user changes all the files and file names everything is fine. But if the user wishes to change only one or two file(s) and filename(s) the MySql update statement ends up having some of the variables empty thereby effectively deleting the existing filenames in the record instead of leaving them alone. As usual I have searched stackoverflow and google before asking for help and I have not found anything that is really pertinent. Here is the applicable code.
<?php
session_start();
$id = $_SESSION['id'];
//This is the directory where images will be saved
$target = "imgs/";
// "http://www.surfcup.com/travel_site/images/ ";
$targetlogo = $target . basename( $_FILES['imageLogo']['name']);
$targetpic1 = $target . basename( $_FILES['image1']['name']);
$targetpic2 = $target . basename( $_FILES['image2']['name']);
$targetpic3 = $target . basename( $_FILES['image3']['name']);
$targetpic4 = $target . basename( $_FILES['image4']['name']);
$targetpic5 = $target . basename( $_FILES['image5']['name']);
//This gets all the other information from the form
$logo=($_FILES['imageLogo']['name']);
$pic1=($_FILES['image1']['name']);
$pic2=($_FILES['image2']['name']);
$pic3=($_FILES['image3']['name']);
$pic4=($_FILES['image4']['name']);
$pic5=($_FILES['image5']['name']);
// Connects to Database
mysql_connect("localhost", "surfcup_HotAdmin","password") or die ('I cannot connect to the database because: ' .mysql_error());
mysql_select_db("surfcup_hotels") or die('I cannot connect to the database because: .mysql_error());
$query="UPDATE Hotels
SET
hotel.imageLogo = '".$logo."',
hotel.image1 = '".$pic1."',
hotel.image2 = '".$pic1."',
hotel.image3 ='".$pic1."',
hotel.image4 = '".$pic1."',
hotel.image5 = '".$pic1."'
WHERE Hotels.id='".$id."'";
mysql_query($query) or die ('Error Updating Hotel '.mysql_error());
//stuff to upload the files below
?>
I think I either need to check if the variables are null and somehow not up load them or stop the database from accepting null entries. The later though would make the user have to add 6 files when he/she creates a record. What if they only had 5 or 3? I can't seem to get my head around how I would check if the variables are null and only upload the ones with filenames in them in the UPLOAD statement. Thanks again, in advance, for all your help.
Dave
I think a better way of doing this is to build your query dynamically. For example:
$images = array();
$images[] = ($_FILES['imageLogo']['name']);
$images[] = ($_FILES['image1']['name']);
$images[] = ($_FILES['image2']['name']);
$images[] = ($_FILES['image3']['name']);
$images[] = ($_FILES['image4']['name']);
$images[] = ($_FILES['image5']['name']);
// Looping index to determine which hotel image it is
$index = 0;
// Start building query
$query = "UPDATE Hotels SET hotel.imageLogo = '".$images[0]."'";
// Loop through images and check if empty string
foreach($images as $image)
{
if(!empty($image) && $index != 0)
{
// Image name found, add to query
$query .= " hotel.image".$index." = '".$image."',";
}
// First hotel image iteration needs to be 1
$index++;
}
// Finish query
$query .= " WHERE Hotels.id='".$id."'";
You can try this. Basically it checks if the value is empty. If it is not, then it adds the value to the array. At the end we implode the array into a string that we will add to the your query. In the example I only did a few of the images, but you should get the point. It should work barring syntax errors in my code.
Although I will say that this is not the best way to do it. You can definitely improve on this and make it more secure and efficient.
$uploaded_images = array();
if(!empty($logo)){
$uploaded_images[] = "hotel.imageLogo = '".$logo."'";
}
if(!empty($pic1)){
$uploaded_images[] = "hotel.image1 = '".$pic1."'";
}
if(!empty($pic2)){
$uploaded_images[] = "hotel.image2 = '".$pic2."'";
}
$values_to_set = implode(', ', $uploaded_images);
$query= "UPDATE Hotels SET " . $values_to_set . " WHERE Hotels.id='" . $id . "'";

Categories