value of variable vanishes - php

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;
}
?>

Related

PHP - Display different image based on mysql row result

Sorry for my English.
I'm learning PHP and I try to create a small member area, I think it's a good way to learn.
In my member area, some members are "verified" and some are not.
How can I display different pics based on data stored in Mysql using PHP?
What I want is to display "Picture1" if "1" is the value stored in a MySQL column and "Picture2" if "2" is the value, etc... You are "unverified member" so you see picture 1, verified member see picture 2...
I know how to SELECT data using MySQLi but I can't find what I have to do next?
Thank you.
Lets assume that you have a database named as db and table as tb with columns name and verify. Name is string and verify is Boolean. Also verify stored 1 if user is verified and 0 it isn't.
so, you can do it by iteration statements (either by using if else or by switch statements)
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query="SELECT * FROM `tb`";
$sql=$conn->query($query);
if($sql->num_rows>0)
{
while($row=$sql->fetch_assoc())
{
//display name
echo $row['name'];
//check if user is verified or not
//using if else statement
if($row['verify']=="0")
{
echo '<img src="./picture1.jpg">';
}
else
{
echo '<img src="./picture2.jpg">';
}
//using switch case
switch($row['verify'])
{
case(0):
{
echo '<img src="./picture1.jpg">';
}
case(1);
{
echo '<img src="./picture2.jpg">';
}
}
//remember i have used both methods hence it will show the image twice , i did it just you possible ways , you choose any one from it.(if else or switch case)
}
}
$conn->close();
?>
There's a few ways. If it will always follow a number system... use this:
$picture = "Picture" . $verified;
// example: $picture = "Picture1", if $verified = 1
Lots of ways to concatenate...
$pic = "Picture$verified.png";
$picture = "Picture" . $verified . ".jpeg";
It will just depends on how you have it setup..
switch($verified){
case 1:
$picture = "Picture1";
break;
case 2:
$picture = "Picture2";
break;
case default:
$picture = "Picture1";
break;
}
Another way...
if($verified == 1){ $picture = "Picture1"; } else { $picture = "Picture2"; }
The reason for the switch statement, or this if/else statement is that it can account for verified being equal to 0, null, or another non 1 or 2 value that may be stored in the database for whatever reason. With the first example, if $verified (verified column = to 1 or 2) has an odd value, the picture# may not actually be real.
Now, of course this is just to handle the different ways. You would have to make sure it lines up properly with your actual image...
$picture = "Picture1"; // would be dynamic to code above
$ext = ".png"; // optional, could be added into the $picture variable above easily too
$filePath = "/images/user_uploads/"; // make sure path is correct
$filePathName = $filePath . $picture . $ext;
// see? We combine path/pictureName/extension to create an image URL
if(file_exists($filePathName) !== false){ // make sure exists
$imageCode = "<img src='$filePathName' alt='Not Found'>";
} else {
// file does not exist! ut oh!
}
It depends on how your images map to the values in your database, but assuming you have a simple relationship like:
1: /images/1.jpg
2: /images/2.jpg
Simply grab the data from your database and map it to a variable (in my example it's $image), and then concatenate it with the filepath inside an echo statement inside of an <img src> attribute:
<img src="<?php echo '/images/' $image . '.jpg'; ?>"/>
This will output:
<img src="/images/1.jpg"/>
<img src="/images/2.jpg"/>
Based on the chosen image.
Now you just have to set that variable to the right value based on your conditional:
<?php
if ($authenticated) {
$image = 1;
}
else {
$image = 2;
}
?>
<img src="<?php echo '/images/' $image . '.jpg'; ?>"/>
Or more succinctly with a ternary:
<?php ($authenticated ? $image = 1 : $image = 2) ?>
<img src="<?php echo '/images/' $image . '.jpg'; ?>"/>
Try this:
<img src="<?php echo "/pictures/Picture{$number}.jpg"; ?>" />

Variable for file directory path not being recognized

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..

Php image show issue

I'm confused! Basically i've a form with 3 field ex: subject, image, message. So,
(1) If i upload image it's should be show image,
(2) if i don't upload image it's should be show just only subject and message no image box and
(3) if i don't upload image and if there are a youtube link in message box then it's should be show the vedio. **
Following is my php code, but i can't solved the number 3 point! **
<?php
if(empty($imgname))
{
echo '';
}
elseif(!empty($imgname))
{
echo "<span class='vedio'>";
echo '<img src="' . $upload_path . '/' . $imgname . '" width="195" height="130"
style=" background-color:f2f4f6;" />';
echo "</span>";
}
else
{
echo "<span class='vedio'>";
require_once("func.php");
if (preg_match('%(?:youtube\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)
([^"&?/ ]{11})%i', $msg, $match))
{
// echo $video_id = $match[1];
}
echo #get_youtube_embed($video_id = $match[1]);
echo "</span>";
}
?>
Any Idea or Solution that would be better for me.
Shibbir.
You'll never get into your else statement because of your preceding if conditions. In ALL cases, $imgname will either be empty, or not empty.
To demonstrate further:
if (empty($imgname)) {
// ... First condition
} else if (!empty($imgname)) {
// ... Last possible condition
} else {
// Will never reach here because $imgname will
// fall into one of the two of the above conditionals.
}
It's difficult to add to your code without full context, but it seems you may want to include the following after the above code (not with):
if(!empty($msg) && preg_match('%(?:youtube\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)
([^"&?/ ]{11})%i', $msg, $match)) {
require_once("func.php");
echo "<span class='vedio'>";
echo #get_youtube_embed($match[1]);
echo "</span>";
}

PHP: if image exists show image else show different image

i am making a login system with registration and a profile page in php and i am trying to make a profile picture work.
if the user has not uploaded a profile picture yet then make it show a "no profile picture" image if the user has uploaded a profile picture make make it show the image that he has uploaded.
Right now it only show the default picture, noprofile.png.
< img src="uploads/< ? echo "$username" ? >/noprofile.png">
i want it to show icon.png if icon.png has been uploaded and if it hasnt been uploaded make it show, noprofile.png.
Just run it through the logic, using file_exists:
$image="/path/on/local/server/to/image/icon.png";
$http_image="http://whatever.com/url/to/image";
if(file_exists($image))
{
echo "<img src=\"$http_image\"/>\n";
}
else
{
echo "<img src=\"uploads/$username/noprofile.png\"/>\n";
}
Check to see if the file has been uploaded by using file exists. If the file exists, use that url else use the default noprofile.png.
you could make a column in the DB to store a value if it has been uploaded or not.
OR
you could see if the file exists.
<?php
if (file_exists('uploads/' . $username . '/icon.png')) {
echo '<img src="uploads/' . $username . '/icon.png">';
}
else {
echo '<img src="uploads/' . $username . '/noprofile.png">';
}
?>
<?php
$img = file_exists(sprintf('/path/to/uploads/%s/icon.png', $username))
? 'icon.png' : 'noprofile.png';
?>
<img src="uploads/<?php printf('%s/%s', htmlspecialchars($username), $img) ?>">
You could use http://us3.php.net/file_exists to check if the image file is there.
Another alternative is - assuming you keep your user info in a database - have a column with the image name. Since you have to retrieve info from your user table anyway, check to see if that column is NULL or blank. If it is, the user has not uploaded an image yet.
Then, in the page you display the user photo, you might have code something like this:
$userPhoto = ($photoName)? $photoName : 'placeholder';
echo '<img src="uploads/'.$userPhoto.'.png" />
Assuming the filepaths are correct, here's what you do...
<?php $filename = "uploads/".$username;
$imgSrc = file_exists($filename) ? $filename : "uploads/noprofile.png"; ?>
<img src=<?php echo $imgSrc?>
Use onerror attribute in img tag
<img onerror="this.src= 'img/No_image_available.png';" src="<?php echo $row['column_name ']; ?>" />

php - Decide whether an image exist and if it does show it

I have a code that shows a different image depending where on the page I am, but some places don't have an image so it displays a "no image" icon. I want to add a condition that checks if there really is an image in the given path and if returns false don't do anything. I have no idea how to do it.
This is the original code:
<?php
$search=get_search_query();
$first=$search[0];
if ($first=="#"){
echo "<html>";
echo "<img src='http://chusmix.com/Imagenes/grupos/".substr(get_search_query(), 1). ".jpg'>";
}
?>
What I need to know is which function do I use to get a true/false of that image path. Thanks
Use file_exists
$image_path = 'Imagenes/grupos/' . substr(get_search_query(), 1) . '.jpg';
if (file_exists($image_path)) {
echo "<img src='http://chusmix.com/Imagenes/grupos/".substr(get_search_query(), 1). ".jpg'>";
} else {
echo "No image";
}
http://php.net/manual/en/function.file-exists.php
You can use file_exists

Categories