Variable for file directory path not being recognized - php

so far I've successfully moved an uploaded image to its designated directory and stored the file path of the moved image into a database I have.
Problem is, however, is that the img src I have echoed fails to read the variable containing the file path of the image. I've been spending time verifying the validity of my variables, the code syntax in echoing the img src, and the successful execution of the move/storing code, but I still get <img src='' when I refer to the view source of the page that is supposed to display the file path contained in the variable.
I believe the file path is stored within the variable because the variable was able to be recognized by the functions that both moved the image to a directory and the query to database.
My coding and troubleshooting experience is still very adolescent, thus pardon me if the nature of my question is bothersomely trivial.
Before asking this question, I've searched for questions within SOF but none of the answers directly addressed my issue (of the questions I've searched at least).
Main PHP Block
//assigning post values to simple variables
$location = $_POST['avatar'];
.
.
.
//re-new session variables to show most recent entries
$_SESSION["avatar"] = $location;
.
.
.
if (is_uploaded_file($_FILES["avatar"]["tmp_name"])) {
//define variables relevant to image uploading
$type = explode('.', $_FILES["avatar"]["name"]);
$type = $type[count($type)-1];
$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
$rdn = substr(str_shuffle($chars), 0, 15);
//check image size
if($_FILES["avatar"]["size"] > 6500000) {
echo"Image must be below 6.5 MB.";
unlink($_FILES["avatar"]["tmp_name"]);
exit();
}
//if image passes size check continue
else {
$location = "user_data/user_avatars/$rdn/".uniqid(rand()).'.'.$type;
mkdir("user_data/user_avatars/$rdn/");
move_uploaded_file( $_FILES["avatar"]["tmp_name"], $location);
}
}
else {
$location = "img/default_pic.jpg";
}
HTML Block
<div class="profileImage">
<?php
echo "<img src='".$location."' class='profilePic' id='profilePic'/>";
?><br />
<input type="file" name="avatar" id="avatar" accept=".jpg,.png,.jpeg"/>
.
.
.
View Source
<div class="profileImage">
<img src='' class='profilePic' id='profilePic'/><br />
<input type="file" name="avatar" id="avatar" accept=".jpg,.png,.jpeg"/>
.
.
.

Alright, I've finally found the error and was able to successfully solve it!
Simply declare a avatar session variable to the $location variable after updating the table, update the html insert by replacing all $location variables with $_SESSION["avatar_column"] and you are set!
PHP:
$updateCD = "UPDATE users SET languages=?, interests=?, hobbies=?, bio=?, personal_link=?, country=?, avatar=? WHERE email=?";
$updateST = $con->prepare($updateCD);
$updateST->bind_param('ssssssss', $lg, $it, $hb, $bio, $pl, $ct, $location, $_SESSION["email_login"]);
$updateST->execute();
$_SESSION["avatar"] = $location; //Important!
if ($updateST->errno) {
echo "FAILURE!!! " . $updateST->error;
}
HTML:
<div class="profileImage">
<?php
$_SESSION["avatar"] = (empty($_SESSION["avatar"])) ? "img/default_pic.jpg" : $_SESSION["avatar"] ;
echo "<img src='".$_SESSION["avatar"]."' class= 'profilePic' id='profilePic'> ";
?>
.
.
.
Thank you!

try this code
<?php
error_reporting(E_ALL);
ini_set('display_errors','on');
$location = ""; //path
if($_POST && $_FILES)
{
if(is_uploaded_file())
{
// your code
if(<your condition >)
{
}
else
{
$location = "./user_data/user_avatars/".$rdn."/".uniqid(rand()).'.'.$type;
if(!is_dir("./user_data/user_avatars/".$rdn."/"))
{
mkdir("./user_data/user_avatars/".$rdn."/",0777,true);
}
move_uploaded_file( $_FILES["avatar"]["tmp_name"], $location);
}
}
else
{
$location = "img/default_pic.jpg";
}
}
?>
Html Code :-
<div>
<?php
$location = (empty($location)) ? "img/default_pic.jpg" : $location ;
echo "<img src='".location."' alt='".."'> ";
?>
</div>
If it helpful don't forget to marked as answer so another can get correct answer easily.
Good Luck..

Related

value of variable vanishes

I do not understand what is happening with my variables, the values all vanish / become empty within the function. I don't have anything within the function. I believe that I am doing the 'checks' correctly '==' and the assignments correctly '='. Regardless of what i try, i continue to get the 'file doesn't exist result'. and if i var_dump to see what the value of $cID or $check, they come back as empty ''.
function gt_masthead($cID='3', $check=false, $str=''){ //assign value to var
$check == file_exists('./' . $cID . 'bg-userProfile.jpg'); //file exists?
//echo '<h1> / ' . $cID . ' / ' . $check . ' </h1>';
dumpVar($cID); //test
if($check == 1){
// file exists, show
$str = '<img class=" img-fluid" style="width: 100%;" src="./3bg-userProfile.jpg" alt="Card image cap">';
}else{
// file does not exist, show default
$str = '<img class=" img-fluid" style="width: 100%;" src="./img_logoMarvel.gif" alt="Card image cap">';
}
return $str;
}
Try this code instead:
<?php
function gt_masthead($cID, $image = "bg-userProfile.jpg", $default = "img_logoMarvel.gif") { //assign value to var
//check if given image file exists
if(file_exists("./{$cID}{$image}")) {
//if it does exist, set the displayImage variable to the path of the image.
$displayImage = "./{$cID}{$image}";
} else {
//if it does not exist, set the displayImage variable to the path of the default image
$displayImage = "./{$default}";
}
//Add the displayImage path to an image element, and return that element.
$str = "<img class='img-fluid' style='width:100%;' src='{$displayImage}' alt='Card image cap'>";
return $str;
}
?>
The usage of this code is pretty simple. You call it like this:
gt_masthead("cID number", "image name"); - you can also use variables here, just drop the quotes.
Alternatively, you can also use a 3rd variable to dynamically set the default image if the searched one does not exist.
gt_masthead("cID number", "image name", "default image name");
I commented the code to try to explain what is going on. If you have any questions please ask
Here is a more standard way to write the function, I know the squiggly braces sometimes confused people, but the code is basically the same.
<?php
function gt_masthead($cID, $image = "bg-userProfile.jpg", $default = "img_logoMarvel.gif") { //assign value to var
//check if given image file exists
if(file_exists("./".$cID.$image)) {
//if it does exist, set the displayImage variable to the path of the image.
$displayImage = "./".$cID.$image;
} else {
//if it does not exist, set the displayImage variable to the path of the default image
$displayImage = "./".$default;
}
//Add the displayImage path to an image element, and return that element.
$str = "<img class='img-fluid' style='width:100%;' src='".$displayImage."' alt='Card image cap'>";
return $str;
}
?>

How correctly refresh included PHP file?

I'm just a persistent beginner and I've met another obstacle in my way, so I hope that you'll help me one more time... :) I've got that HTML:
<div class='hold'><?php include 'image.php'; ?></div>
<div class='refresh'>Get new image</div>
And that PHP code:
<?php
$dir = 'images/';
$img = array();
if(is_dir($dir)) {
if($od = opendir($dir)) {
while(($file = readdir($od)) !== false) {
if(strtolower(strstr($file, '.'))==='.jpg') {
array_push($img, $file);
}
}
closedir($od);
}
}
$id = uniqid();
$smth = array_rand($img, 1);
echo '<img src=' . $dir.$img[$smth] . '?' . $id . ' width="200px" height="50px" />';
echo '<input type="hidden" value=' . $id . ' />';
?>
So now when I'm looking at my page I see in the <div class='hold'></div> my img from the folder images, and it's allright. BUT when I click on the <div class='refresh'></div> I obviously want to get another img from my folder, but I dunno how to accomplish that trick correctly.
I know that first answer will be USE AJAX, and I know that I can do something like
function loadGraphic() {
$('.hold').load('image.php');
};
loadGraphic();
and then $('.refresh').click(loadGraphic); but when I'm trying to do that in response from server I get TWO THINGS: image.php and, of course, something like car.jpg?573c4e010c7f6... But I very-very wanna get just ONE looking like
car.jpg?573c4e010c7f6
or
image.php?573c4e010c7f6 - I don't care...
So... I hope you've got my concept... maybe I'm asking for miracle - I dunno! Any, absolutely any help will be appreciated :)
Try it the following way:
JS function:
function loadGraphic() {
$.get("image.php", function(data) {
$(".hold").html(data);
});
};
Html:
<div class='refresh' onclick='loadGraphic()'>Get new image</div>

PHP, using $_FILES and $_POST at the same time

I have a problem in using $_FILES and $_POST at the same the because I have a form to upload an image and some data bus when I use one of them it works but when I used the other one id doesn't work.
my code is :
<?php
include 'debugging.php';
//phpinfo();
echo '<br />';
echo '<h1>Image Upload</h1>';
//create a form with a file upload control and a submit button
echo <<<_END
<br />
<form method='post' action='uplaodex.php' enctype='multipart/form-data'>
Select File: <input type='file' name='picName' size='50' />
name: <input type='text' name='usName' size='50' />
username : <input type='text' name='usUsername' size='50' />
pass: <input type='password' name='usPass' size='50' />
email: <input type='text' name='usEmail' size='50' />
<br />
<input type='submit' value='Upload' />
<input type="hidden" name="submit" value="1" />
</form>
<br />
_END;
//above is a special use of the echo function - everything between <<<_END
//and _END will be treated as one large echo statement
//$_FILES is a PHP global array similar to $_POST and $_GET
if (isset($_FILES['picName'])and isset($_POST['submit'])) {
//we access the $_FILES array using the name of the upload control in the form created above
//
//create a file path to save the uploaded file into
$name = "images//" . $_FILES['picName']['name']; //unix path uses forward slash
//'filename' index comes from input type 'file' in the form above
//
//move uploaded file from temp to web directory
if (move_uploaded_file($_FILES['picName']['tmp_name'], $name)) {
// Create the file DO and populate it.
include 'Do_profile.php';
$file = new Do_profile();
//we are going to store the file type and the size so we get that info
$type = $_FILES['picName']['type'];
$size = $_FILES['picName']['size'];
$usName = trim($_POST['usName']);
$usUsername = trim($_POST['usUsername']);
$usPass = trim($_POST['usPass']);
$usEmail = trim($_POST['usEmail']);
$file->FileName = $name; //$name is initialised previously using $_FILES and file path
$file->FileSize = $size;
$file->Type = $type;
$file->usName = $usName;
$file->usUsername = $usUsername;
$file->usPass = $usPass;
$file->usEmail = $usEmail;
if ($file->save()) {
//select the ID of the image just stored so we can create a link
//display success message
echo "<h1> Thankyou </h1><p>Image stored successfully</p>";
//this above line of code displays the image now stored in the images sub directory
echo "<p>Uploaded image '$name'</p><br /><img src='$name' height='200' width='200'/>";
//create alink to the page we will use to display the stored image
echo '<br><a href="Display.php?id=' . $fileId . '">Display image ' .
$file->FileName . '</a>';
} else
echo '<p class="error">Error retrieving file information</p>';
}
else {
echo '<p class="error"> Oh dear. There was a databse error</p>';
}
} else {
//error handling in case move_uploaded_file() the file fails
$error_array = error_get_last();
echo "<p class='error'>Could not move the file</p>";
// foreach($error_array as $err)
// echo $err;
}
echo "</body></html>";
?>
I don't know what is the problem, any help??
Everything inside that if (isset($_FILES['picName'])and isset($_POST['submit'])) doesn't work because the superglobal $_FILES is probably not having a key named picName. To check this out, try var_dump-ing the $_FILES, like var_dump($_FILES);
By the output of the var_dump you'd get to know if there is any content inside $_FILES. And if it is populated, just see what the key name is and, access the file by using that key.
But if the array is empty, there may be some mis-configurations in PHP, or APACHE.
One possible fix would be setting file_uploads = On in the ini file for php.
Hope it helps!
You have to validate the size of the file if you want to do an isset. I don't know if this is works, but the better way for do that is check first the size for validate if isset or was send to the server.
Then, in your <form method='post' action='uplaodex.php' enctype='multipart/form-data'> you have to create another PHP file with the name uplaodex.php where you'll send al the data. So, your code with be like the below code following and considering the step 1. This will be your uploadex.php
$name_file = $_FILES['picName']['name'];
$type = $name_file['type'];
$size = $name_file['size'];
$tmp_folder = $name_file['tmp'];
$usName = trim($_POST['usName']);
$usUsername = trim($_POST['usUsername']);
$usPass = trim($_POST['usPass']);
$usEmail = trim($_POST['usEmail']);
if ( $size > 0 ) {
//REMOVE another slash images//
$name = "images/" . $name_file; //unix path uses forward slash
//'filename' index comes from input type 'file' in the form above
//
//move uploaded file from temp to web directory
if ( move_uploaded_file($tmp_folder, $name) ) {
// Create the file DO and populate it.
include 'Do_profile.php';
$file = new Do_profile();
$file->FileName = $name; //$name is initialised previously using $_FILES and file path
$file->FileSize = $size;
$file->Type = $type;
$file->usName = $usName;
$file->usUsername = $usUsername;
$file->usPass = $usPass;
$file->usEmail = $usEmail;
if ($file->save()) {
//USE PRINTF
printf('<h1> Thankyou </h1><p>Image stored successfully</p><br>
<p>Uploaded file: %s</p>. <img src="%s" height="200" width="200" />',
$name_file, $name );
#WHAT IS $fileId? In which moment was define?
//echo '<br><a href="Display.php?id=' . $fileId . '">Display image ' .
$file->FileName . '</a>';
}
else
echo '<p class="error">Error retrieving file information</p>';
}
else {
echo '<p class="error"> Oh dear. There was a databse error</p>';
} //ENDIF OF if (move_uploaded_file($_FILES['picName']['tmp_name'], $name))
} //ENDIF OF if ( $size > 0 )
#ELSE OF YOUR if ( $size > 0 )
else {
//error handling in case move_uploaded_file() the file fails
$error_array = error_get_last();
echo "<p class='error'>Could not move the file</p>";
// foreach($error_array as $err)
// echo $err;
}
I solved the problem, you can't perform $_FILES and $_post at the same time or one of them inside the other.
start with $_Post and then $_FILES and outside the $_FILES run your saving function
thats it

PHP form function is working but returns blank page

I'm working on a function to upload images to my website fileserver and at the same time would create a thumb preview and create an entry to my mysql database. So long the function to upload_image() is working, it uploads the image and creates a thumb perfectly.
The issue is, that when I click the submit button to upload the image selected, the PHP function do its job but will return a BLANK PAGE. Yes, I know, "another blank page of death question, go find all the other 53 posts related to this question and find a solution" right? Well, it's not that simple.
I have tried every single method in those questions and another bunch that I've found over this forsaken place called internet and nothing works for me, I always get the same Blank Page of death with no warning or error.
What have I tried would you ask? The following would just represent a relevant set of solutions that I recall:
Configuring PHP.INI's options for error: DONE. Even creating the log file for every single detailed error.
Overriding PHP.INI's options from the php file function with the settings: DONE. Also I have used a script from some answers that override error log protocol.
Place an exit('wtf') function from start to bottom to see if its an Syntax error or an error on a certain line: DONE. Every single line will print WTF on the god forsaken Blank Page.
Well, there are other solutions I have tried, be my guest and offer some answers and I would tell you if I have already tried it.
Lets get to it then. My HTML code that calls the php file is:
<form action="assets/php/image_uploader.php" method="post" enctype="multipart/form-data">
<input type="file" name="myfile" id="fileToUpload">
</br>
</br>
<input type="text" name="title" value="Titulo" size="64">
<br>
<br>
<input type="submit" value="Upload Image" name="submit">
</form>
And my image_uploader.php code is:
<?php
function upload_image()
{
$root = realpath($_SERVER["DOCUMENT_ROOT"]);
$name = "image_" . date('Y-m-d-H-i-s') . "_" . uniqid() . ".jpg";
$type= $_FILES["myfile"]["type"];
$size= $_FILES["myfile"]["size"];
$temp= $_FILES["myfile"]["tmp_name"];
$error= $_FILES["myfile"]["error"];
if ($error > 0)
{
die("Error uploading file! code $error.");
}
else
{
if($type=="image/png" || $size > 2000000)//condition for the file
{
die("Format not allowed or file size too big!");
}
else
{
if(move_uploaded_file($temp, $root . "/images/fulls/" . $name))
{
list($ancho, $alto) = getimagesize($root . "/images/fulls/" .$name);
$nuevo_alto = 212;
$nuevo_ancho = 212;
$dx = 0;
$dy = 0;
$sx = 0;
$sy = 0;
if($ancho == $alto)
{
}
else
{
if($ancho > $alto)
{
$nuevo_ancho = $ancho * (212/$alto);
}
else
{
$sy = $alto/2 - $nuevo_alto/2;
$alto = $ancho;
}
}
$thumb = imagecreatetruecolor($nuevo_ancho, $nuevo_alto);
$origen = imagecreatefromjpeg($root . "/images/fulls/" .$name);
imagecopyresampled($thumb, $origen, $dx, $dy, $sx, $sy, $nuevo_ancho, $nuevo_alto, $ancho, $alto);
imagejpeg($thumb, $root . "/images/thumbs/" .$name);
imagedestroy($thumb);
echo "The file ". basename( $_FILES["myfile"]["name"]). " has been uploaded.";
}
}
}
}
if(isset($_POST['submit']))
{
upload_image();
}
?>
try this:
$new_file = $root . "/images/fulls/" . $name;
copy($temp, $new_file);
if(!is_file($new_file)) {
die('cannot copy file');
}
also wrap main part with:
try{
}
catch(Exception $ex) {die('['.$ex->getLine().'] '.$ex->getMessage());}
Placed the code into the HTML file which was renamed later to have the extension .php and called the function in the form section as:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" enctype="multipart/form-data">
<input type="file" name="myfile" id="fileToUpload">
</br>
</br>
<input type="text" name="title" value="Titulo" size="64">
<br>
<br>
<input type="submit" value="Upload Image" name="submit">
</form>
And now it works as if it was magic, I do not know if htmlspecialchar() function has anything to do with it, but now the code works with no errors. Therefore I would post this as an answer but reminding you to not consider this as a solution to the BLANK PAGE death screen.

php image checkbox deleter

I am having trouble making a image deleter in php i do not know what is wrong
PHP:
<?php if (isset($_POST['dcheck'])) {
$img_dir = "Uploads/";
$image = $_POST['dcheck'];
mysql_query("DELETE FROM Photos WHERE PhotoNumber = '".$image."'") or die(mysql_error());
echo 'The image(s) have been successfully deleted.';
} else{
echo 'ERROR: unable to delete image file(s)!';
}
?>
HTML:
<form action="Admin3.php" method="post">
<?php
while($check = mysql_fetch_array($query2)){
echo '<img class="images2" src= "/PhotographyMML/Uploads/resized' . $check['PhotoName'] . $check['PhotoType'] . '" height="100" width ="100" ><input type="checkbox" name="dcheck[]" value="'. $check['PhotoNumber'] .'" />';
}
?>
<input type="submit" value="Delete Image(s)" />
</form>
Your dcheck variable is an array. You will want to create an outer loop around the existing query code you have and foreach through the array, deleting each time.
<?php if (isset($_POST['dcheck'])) {
$img_dir = "Uploads/";
foreach ($_POST['dcheck'] as $image) {
mysql_query("DELETE FROM Photos WHERE PhotoNumber = '".$image."'") or die(mysql_error());
echo 'The image(s) have been successfully deleted.';
} else{
echo 'ERROR: unable to delete image file(s)!';
}
}
?>
A small optimization would be to alter the query so it uses WHERE A small optimization would be to alter your delete query so that it uses WHERE PhotoNUmber IN (1, 2 ...).
This would cause your deletion to happen in one query rather than N queries.
What seems to be missing is any code to actually remove the original file you're alluding to. That would require some sort of file deletion function typically utilizing http://php.net/manual/en/function.unlink.php

Categories