Can't make PHP function work inside HTML inside PHP - php

I wrote this code, it gets an image from a link that varies according to where you are:
<img src='http://chusmix.com/Imagenes/grupos/<?php echo substr(get_search_query(), 1); ?>.jpg'>
I want to make that code run if a PHP condition proves true, but I cannot make it work. It seems that the function doesn't return a value instead it takes the link textually. I mean it goes to http://chusmix.com/Imagenes/grupos/.jpg literally. However the code works correctly by itself.
This is the PHP code:
<?php
$search=get_search_query();
$first=$search[0];
if ($first=="#"){
echo "<html>";
echo "<img src='http://chusmix.com/Imagenes/grupos/<?php echo substr(get_search_query(), 1); ?>.jpg'>";
}
?>

You are already inside the php tag. So there is no need for <?php and ?>.
Try:
echo "<img src='http://chusmix.com/Imagenes/grupos/".substr($search,1).".jpg'>";

Replace line
echo "<img src='http://chusmix.com/Imagenes/grupos/<?php echo substr(get_search_query(), 1); ?>.jpg'>";
with
echo "<img src='http://chusmix.com/Imagenes/grupos/" . substr(get_search_query(), 1) . ".jpg'>";

Related

How can I add an image inside a shortcode

I have an image displayed in the following manner:
<img src="<?php bloginfo('template_directory')?>/images/logo/logo.png">
Now, however, I want to create a shortcode that has an attribute and uses that same image inside it. So I tried the following:
add_shortcode('scrollTop', function(){
echo "<a href='#content' class='content'>";
echo "<img src='bloginfo('"template_directory"')/images/logo/logo.png'">;
echo "skipping content";
echo "</a>";
});
Its a syntax error I assume, but am struggling to find a way around.
How can I add the image inside the shortcode?
Use the concatenation operator and correct single quotes inside the bloginfo function.
add_shortcode('scrollTop', function(){
echo "<a href='#content' class='content'>";
echo "<img src='" . bloginfo('template_directory') . "/images/logo/logo.png'>";
echo "skipping content";
echo "</a>";
});
Also make sure to not use echo inside your shortcode to display something. Use return instead. See this question for more information.
add_shortcode('scrollTop', function(){
return "<a href='#content' class='content'>
<img src='" . bloginfo('template_directory') . "/images/logo/logo.png'>
skipping content
</a>";
});

How to use strpos() to check a variable's path?

I have a home page that shows some uploaded images.
I take it from the database and I use strpos() to check the URL due to directory problems, and it works fine:
if(strpos($row['cImage'],"http://") === FALSE){
echo "<img src='serintercement/".$row['cImage']."' style='width: 107px; height:102px;' />";
}else{
echo "<img src='".$row['cImage']."' style='width: 107px; height:102px;' />";
}
I need to use the same logic in a page that shows the clicked image, but it has a variable for it and I'm struggling to fix this since it's a different way to write:
<img src='<?php echo $resultData->cImage; ?>'/>
I can't fix the directory problem. How can I use strpos() similarly for this second code?
You can do it like this.
if(strpos($resultData->cImage,"http://") === FALSE){
echo "<img src='serintercement/".$resultData->cImage."' style='width: 107px; height:102px;' />";
}else{
echo "<img src='".$resultData->cImage."' style='width: 107px; height:102px;' />";
}
Better option is you can define a function like this and call it
checkImage($row['cImage']);//to be called in your first page
checkImage($resultData->cImage);//to be called in your second page
function checkImage($image)
{
if(strpos($image,"http://") === FALSE){
echo "<img src='serintercement/".$image."' style='width: 107px; height:102px;' />";
}else{
echo "<img src='".$image."' style='width: 107px; height:102px;' />";
}
}
You should be able to check the path similarly - as long as the property of the object is set and a string, strpos() can be used.
if(strpos($resultData->cImage,"http://") === FALSE){
echo "<img src='serintercement/".$resultData->cImage."' />";
}else{
echo "<img src='".$resultData->cImage."' />";
}
If these cImage strings are coming from your database, you could just correct them in the query call.
For example, if you are using MySQL, you could prepare the data using LOCATE() AND CONCAT() like this:
SELECT
IF(LOCATE('http',`cImage`)!=1,CONCAT('serintercement/',`cImage`),`cImage`) `new_cImage`
FROM ...
Moving the conditional process to your query, will make your "displaying" code read more smoothly because all of the preparations are completed ahead of time.
Outside of that, you can make your code more DRY by not repeating the html parts that come before and after the image variable...
This is an echo with an inline condition (not everyone likes this style):
echo "<img src=\"",(strpos($resultData->cImage,"http")===0?'':'serintercement/'),"{$resultData->cImage}\" style=\"width:107px;height:102px;\" />\n";
This is a separated conditional:
echo "<img src=\"";
if(strpos($resultData->cImage,"http")!==0){
echo 'serintercement/'
}
echo "{$resultData->cImage}\" style=\"width:107px;height:102px;\" />\n";
This is a function call if you have to do this multiple times in the same script:
function fixPath($img){
if(strpos($img,"http")===0){
return $img;
}
return "serintercement/$img";
}
echo "<img src=\"",fixPath($resultData->cImage),"\" style=\"width:107px;height:102px;\" />\n";
Notice that I am only checking for http and that I am very accurately checking that it comes from the first position in the string. Across all these alternatives, the point I am making is DRYness (which is a typical pursuit of all programmers). How you chose to implement it comes down to your personal preference.

Why I'm not able to print the whole output to the screen in PHP?

I'm using Slim framework for my project. I've copied the Slim folder to my project directory.
No following is the code I'm having issue with :
PHP Code(requestdemo.php):
<?php
require 'Slim/Slim.php';
/* Invoke the static "registerAutoloader()" function defined within Slim class.
* Register the autoloader is very important.
* Without doing it nothing will work.
*/
\Slim\Slim::registerAutoloader();
//Instantiate Slim class in order to get a reference for the object.
$application = new \Slim\Slim();
$application->get(
'/request',
function()
{
GlOBAL $application;
echo " <br/><b>request methods</b>";
echo "<br/>application->request->getMethod()=".$application->request->getMethod();
echo "<br/>application->request->isGet()=".$application->request->isGet();
echo "<br/>application->request->isPost()=".$application->request->isPost();
echo "<br/>application->request->isPut()=".$application->request->isPut();
echo "<br/>application->request->isDelete()=".$application->request->isDelete();
echo "<br/>application->request->isHead()=".$application->request->isHead();
echo "<br/>application->request->isOptions()=".$application->request->isOptions();
echo "<br/>application->request->isPatch()=".$application->request->isPatch();
echo "<br/>application->request->isAjax()=".$application->request->isAjax();
echo "<br/> <br/><b>request headers</b>";
$headers = $application->request->headers;
foreach($headers as $k=>$v)
{
echo "<br/>$k => $v";
}
echo "<br/> <br/><b>request body</b>";
echo "<br/>body=".$application->request->getBody();
echo "<br/> <br/><b>request variables</b>";
echo "<br/>width=".$application->request->params('width');
echo "<br/>height=".$application->request->params('height');
echo "<br/> <br/><b>request get variables</b>";
echo "<br/>width=".$application->request->get('width');
echo "<br/>height=".$application->request->get('height');
echo "<br/> <br/><b>request post variables</b>";
echo "<br/>width=".$application->request->post('width');
echo "<br/>height=".$application->request->post('height');
echo "<br/> <br/><b>resource uri</b>";
/*From the below line I'm not able to see the output in a browser.*/
echo "<br/>rootUri=".$application->request->getUri();
echo "<br/>resourceUri=".$application->request->getResourceUri();
echo "<br/> <br/><b>request ajax check</b>";
echo "<br/>rootUri=".$application->request->isAjax();
echo "<br/>resourceUri=".$application->request->getResourceUri();
echo "<br/> <br/><b>request helpers</b>";
echo "<br/>content type=".$application->request->getContentType();
echo "<br/>media type=".$application->request->getMediaType();
echo "<br/>host=".$application->request->getHost();
echo "<br/>scheme=".$application->request->getScheme();
echo "<br/>path=".$application->request->getPath();
echo "<br/>url=".$application->request->getUrl();
echo "<br/>user agent=".$application->request->getUserAgent();
});
$application->run();
?>
The file 'requestdemo.php' is present in the directory titled "slimsamples" at location /var/www/slimsamples
As I hit the URL 'http://localhost/slimsamples/requestdemo.php/request' I'm able to see only the part of output in a browser window. From where I'm not able to see the output I've commented in my code. I'm not able to see the output after line resource uri. See the screenshot for further understanding.
Also there is no syntactical error in it then why it's happening I'm not understanding.
Can someone please find out the mistake I'm making here?
Thanks in advance.
Use: request->getUrl()
(You used request->getUri())
See http://dev.slimframework.com/phpdocs/classes/Slim.Http.Request.html#getUrl

how to use urlencode( ) in my example?

I checked php.net and read a few examples of how urlencode( ) works but somehow I just can't get it right. Can someone give me a hand?
it'll be a lot to example so hopefully my brief example would make sense.
I have a page called 2.php and it was called to show some contents of a .txt file choosen in 1.php.
I am told to make a link for 3.php and the link should look something like /3?filename=a.txt
with filename as GET parameter name and Ensure GET parameter value is urlencoded using the urlencode( ) function.
but I'm confused how and where I should put urlencode() to make it work.
I'll paste my 2.php code here...I simplified the codes a bit...
<?php
$fileContents = file("./aaa/" . $_GET["course"] . ".txt");
echo "<table border=\"1\">";
foreach($fileContents as $row)
{
echo "<tr>";
$contents = preg_split("/,/", $row);
foreach($contents as $eachline)
{
echo "<td>";
if(!(preg_match("/#/", $eachline)))
{
echo trim(ucfirst($eachline));
}
else
{
echo trim(strtolower($eachline));
}
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
echo "<a href='./1.php'>Choose another txt file</a><br/>";
echo "or<br/>";
echo "<a href='.3.php?'>Work with this txt file</a>";
?>
BUT…the 3.php option must have a query string appended to it: the name of the text file that was selected in 1, so instead of ./3.php, the url should be something such as ./3?filename=asdf.txt
Use “filename” as the GET parameter name. Ensure the GET parameter value is urlencoded using the urlencode( ) function.
but I'm just not sure how to get it to work....
You can wrap the part that should be url encoded in the function within the string:
$url = 'http://www.google.com?q=' . urlencode($search);
OR in html
http://www.google.com?q=<?php echo urlencode($search); ?>
Where . is the concatenation of 2 outputs.

Echo entire pre-compiled php page

For example if I had the script:
<?php
$page = "My Page";
echo "<title>" . $page . "</title>";
require_once('header.php');
require_once('content.php');
require_once('footer.php');
?>
Is there something I can add to the bottom of that page to show the entire pre-compiled php?
I want to literally echo the php code, and not compile it.
So in my browser I would see the following in code form...
// stuff from main php
$page = "My Page";
echo "<title>" . $page . "</title>";
// stuff from require_once('header.php');
$hello = "Welcome to my site!";
$name = "Bob";
echo "<div>" . $hello . " " . $name . "</div>";
// stuff from require_once('content.php');
echo "<div>Some kool content!!!!!</div>";
// stuff from require_once('footer.php');
$footerbox = "<div>Footer</div>";
echo $footerbox;
Is this possible?
There's no way to do it native to PHP, but you could try to hack it if you just wanted something extremely simplistic and non-robust:
<?php
$php = file_get_contents($_GET['file']);
$php = preg_replace_callback('#^\s*(?:require|include)(?:_once)?\((["\'])(?P<file>[^\\1]+)\\1\);\s*$#m', function($matches) {
$contents = file_get_contents($matches['file']);
return preg_replace('#<\?php(.+?)(?:\?>)?#s', '\\1', $contents);
}, $php);
echo '<pre>', htmlentities($php), '</pre>';
Notes:
Warning: Allowing arbitrary file parsing like I've done with the fist line is a security hole. Do your own authentication, path restricting, etc.
This is not recursive (though it wouldn't take much more work to make it so), so it won't handle included files within other included files and so on.
The regex matching is not robust, and very simplistic.
The included files are assumed to be statically named, within strings. Things like include($foo); or include(__DIR__ . '/foo.php'); will not work.
Disclaimer: Essentially, to do this right, you need to actually parse the PHP code. I only offer the above because it was an interesting problem and I was bored.
echo '$page = "My Page";';
echo 'echo "<title>" . $page . "</title>";';
echo file_get_contents('header.php');
echo file_get_contents('content.php');
echo file_get_contents('footer.php');
For clarity I'd put the title generation in it's own file, then just use a series of echo file_get_contents()...
echo file_get_contents('title.php');
echo file_get_contents('header.php');
echo file_get_contents('content.php');
echo file_get_contents('footer.php');

Categories