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>";
}
Related
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;
}
?>
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..
I'm working on a project and it's something new for me. I'll need to fetch rss content from websites, and display Descripion, Title and Images (Thumbnails). Right now i've noticed that some feeds show thumbnails as Enclosure tag and some others dont. right now i have the code for both, but i need to understand how i can create a conditional like:
If the rss returns enclosure image { Do something }
Else { get the common thumb }
Here follow the code that grab the images:
ENCLOSURE TAG IMAGE:
if ($enclosure = $block->get_enclosure())
{
echo "<img src=\"" . $enclosure->get_link() . "\">";
}
NOT ENCLOSURE:
if ($enclosure = $block->get_enclosure())
{
echo '<img src="'.$enclosure->get_thumbnail().'" title="'.$block->get_title().'" width="200" height="200">';
}
=================================================================================================
PS: If we look at both codes they're almost the same, the difference are get_thumbnail and get_link.
Is there a way i can create a conditional to use the correct code and always shows the thumbnail?
Thanks everyone in advance!
EDITED
Here is the full code i have right now:
include_once(ABSPATH . WPINC . '/feed.php');
if(function_exists('fetch_feed')) {
$feed = fetch_feed('http://feeds.bbci.co.uk/news/world/africa/rss.xml'); // this is the external website's RSS feed URL
if (!is_wp_error($feed)) : $feed->init();
$feed->set_output_encoding('UTF-8'); // this is the encoding parameter, and can be left unchanged in almost every case
$feed->handle_content_type(); // this double-checks the encoding type
$feed->set_cache_duration(21600); // 21,600 seconds is six hours
$feed->handle_content_type();
$limit = $feed->get_item_quantity(18); // fetches the 18 most recent RSS feed stories
$items = $feed->get_items(0, $limit); // this sets the limit and array for parsing the feed
endif;
}
$blocks = array_slice($items, 0, 3); // Items zero through six will be displayed here
foreach ($blocks as $block) {
//echo $block->get_date("m d Y");
echo '<div class="single">';
if ($enclosure = $block->get_enclosure())
{
echo '<img class="image_post" src="'.$enclosure->get_link().'" title="'.$block->get_title().'" width="150" height="100">';
}
echo '<div class="description">';
echo '<h3>'. $block->get_title() .'</h3>';
echo '<p>'.$block->get_description().'</p>';
echo '</div>';
echo '<div class="clear"></div>';
echo '</div>';
}
And here are the XML pieces with 2 different tags for images:
Using Thumbnails: view-source:http://feeds.bbci.co.uk/news/world/africa/rss.xml
Using Enclosure: http://feeds.news24.com/articles/news24/SouthAfrica/rss
Is there a way i can create a conditional to use the correct code and always shows the thumbnail?
Sure there is. You've not said in your question what blocks you so I have to assume the reason, but I can imagine multiple.
Is the reason a decisions with more than two alternations?
You handle the scenario of a feed item having no image or an image already:
if ($enclosure = $block->get_enclosure())
{
echo '<img class="image_post" src="'.$enclosure->get_link().'" title="'.$block->get_title().'" width="150" height="100">';
}
With your current scenario there is only one additional alternation which makes it three: if the enclosure is a thumbnail and not a link:
No image (no enclosure)
Image from link (enclosure with link)
Image from thumbnail (enclosure with thumbnail)
And you then don't know how to create a decision of that. This is what basically else-if is for:
if (!$enclosure = $block->get_enclosure())
{
echo "no enclosure: ", "-/-", "\n";
} elseif ($enclosure->get_link()) {
echo "enclosure link: ", $enclosure->get_link(), "\n";
} elseif ($enclosure->get_thumbnail()) {
echo "enclosure thumbnail: ", $enclosure->get_thumbnail(), "\n";
}
This is basically then doing the output based on that. However if you assign the image URL to a variable, you can decide on the output later on:
$image = NULL;
if (!$enclosure = $block->get_enclosure())
{
// nothing to do
} elseif ($enclosure->get_link()) {
$image = $enclosure->get_link();
} elseif ($enclosure->get_thumbnail()) {
$image = $enclosure->get_thumbnail();
}
if (isset($image)) {
// display image
}
And if you then move this more or less complex decision into a function of it's own, it will become even better to read:
$image = feed_item_get_image($block);
if (isset($image)) {
// display image
}
This works quite well until the decision becomes even more complex, but this would go out of scope for an answer on Stackoverflow.
I have stored images path in database and images in project folder. Now i am trying to view all IMAGES with their PRODUCTS in my HTML template. I have written the following code and its given me an empty images box in the output and when i open that image box in the new tab, it opens the following URL.
http://localhost/cms/1
Kindly tell me the way of referring images in 'img src ' tag.
include 'connect.php';
$image_query = "select * from product_images";
$image_query_run = mysql_query($image_query);
$image_query_fetch = mysql_fetch_array($image_query_run);
if (!$query=mysql_query ("select product_id,name from products")) {
echo mysql_error();
} else {
while ($query_array = mysql_fetch_array($query)) {
echo '</br><pre>';
$product_id = $query_array['product_id'];
echo "<a href='single_product.php?product_id=$product_id' >";
print_r ($query_array['name']);
echo "</a>";
echo "<img src=". $image_query_fetch
['images'] ." alt=\"\" />";
echo '</pre>';
}
}
} else {
echo "You need to Log in to visit this Page";
}
Add your local image path before source
example
echo "<img src='http://localhost/cms/1/". $image_query_fetch['images'] .'" alt=\"\" />";
*Use PHP *
<?php echo "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; ?>
You can use the HTML base tag to set a base URL that relative URLs will be resolved from.
See -> http://www.w3schools.com/tags/tag_base.asp
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