PHP variable with Javascript - php

I want to write PHP code that check few conditions and then trigger JavaScript on the loaded page.
The php file is:
$jwplayer= "<script>jwplayer('video1').setup({playlist:$file});</script>";
$url2= "http://$_SERVER[HTTP_HOST]/index.php";
$url3= "http://$_SERVER[HTTP_HOST]/index3.php";
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if($url2==$url) {
$file= "/media/video.xml";
echo $jwplayer;
}
if($url3==$url) {
$file= "/media/video2.xml";
echo $jwplayer;
}
I'm using PHP include to include the above code.
If the URL of the page is equal to the value of $url2 above, then I want the playlist updated. This would be done by setting $file to "/media/video.xml" and executing the required JavaScript I am attempting to include.

Try this:
$file= "/media/default.xml";
$url = "http://" . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
$url2= "http://$_SERVER[HTTP_HOST]/index.php";
if($url2==$url) {
$file= "/media/video.xml";
}
$jwplayer= "<script>jwplayer(\"video1\").setup({playlist:".$file."});</script>";
echo $jwplayer;

I would start with fixing your syntax errors and go from there:
function jwPlayer($xml) {
echo("<script>jwplayer('video1').setup({playlist:'$xml'});</script>");
}
$url2= "http://" . $_SERVER["HTTP_HOST"] . "/index.php";
$url = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"];
if($url2 == $url) {
$file= "/media/video.xml";
jwPlayer($file);
} else {
jwPlayer("path/to/other/file.xml");
}
Defining a variable after its use will do nothing but cause you problems.

maybe like this
$file = "somefile.xml";
$url2= "http://$_SERVER[HTTP_HOST]/index.php";
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if($url2==$url)
$file= "/media/video.xml";
$jwplayer= "<script>jwplayer(\"video1\").setup({playlist:$file});</script>";
echo $jwplayer;

Try this..
$url2= "http://$_SERVER[HTTP_HOST]/index.php";
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
if($url2==$url) {
$file= "/media/video.xml";
echo $jwplayer= "<script>jwplayer("video1").setup({playlist:$file});</script>";
}
in you code it looks like your trying to get the value of $file by echo'ing the script..
hope that helps

There is a few mistakes within this code.
In the moment you assign this string, the variable $file is undefined, you have to define it first.
$jwplayer= "<script>jwplayer('video1').setup({playlist:$file});</script>"
On a javascript object literal, you must have to quote a string. If you don't the content of the variable $file will become a undefined javascript variable.
{playlist:"$file"} //playlist is a string
Try this
$url2 = "http://$_SERVER[HTTP_HOST]/index.php";
$url = "http://" . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
if($url2==$url) {
$file= "/media/video.xml";
$jwplayer= "<script>jwplayer('video1').setup({playlist:'$file'});</script>";
echo $jwplayer;
}
I'm not sure what do you mean by "constant", but I would do something like this, but I can't tell for sure if this works just with the little information provided in the actual question.
<?php
$url2 = "http://$_SERVER[HTTP_HOST]/index.php";
$url = "http://" . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI];
$file = "";
if($url2==$url) {
$file = "/media/video.xml";
}
?>
<script>
jwplayer('video1').setup({playlist:'<?=$file>'});
</script>

Related

Php url parsing and editing

I searched "the whole" stackoverflow but didn't find a decent answer that works for me. I need to change the host of a url in php.
This url: http://example123.com/query?t=de&p=9372&pl=bb02799a&cat=&sz=400x320&scdid=e7311763324c781cff2d3bc55b2d83327aba111f2db79d0682860162c8a13c24&rnd=29137126
To This: http://example456.com/test?t=de&p=9372&pl=bb02799a&cat=&sz=400x320&scdid=e7311763324c781cff2d3bc55b2d83327aba111f2db79d0682860162c8a13c24&rnd=29137126
I only need to change the domain and the path or file, so far I've got this:
$originalurl = http://example123.com/query?t=de&p=9372&pl=bb02799a&cat=&sz=400....
$parts = parse_url($originalurl);
$parts['host'] = $_SERVER['HTTP_HOST'];
$parts['path'] = '/test';
$modifiedurl = http_build_query($parts);
print_r(urldecode($modifiedurl));
but it echos
scheme=http&host=localhost&path=/test&query=t=de&p=9372&pl=bb02799a&cat=&sz=400...
Please I don't want to use some strpos or something like that as I need it to be variable.
Thanks ;)
$url = 'http://example123.com/query?t=de&p=9372&pl=bb02799a&cat=&sz=400x320&scdid=e7311763324c781cff2d3bc55b2d83327aba111f2db79d0682860162c8a13c24&rnd=29137126';
$query = parse_url($url)['query'];
$newUrl = 'http://www.younewdomain.com/path?' . $query;
You'll have to do some concatenating manually. This works:
$originalurl = "http://example123.com/query?t=de&p=9372";
$parts = parse_url($originalurl);
$new_path = '/test';
$modifiedurl = $parts['scheme'] . "://" . $_SERVER['HTTP_HOST'] . $new_path . (isset($parts['query']) ? "?".$parts['query']:"");
print_r($modifiedurl);
Came up with a different approach:
$url = "http://example123.com/query?t=de&p=9372&pl=bb02799a&cat=&sz=400x320&scdid=e7311763324c781cff2d3bc55b2d83327aba111f2db79d0682860162c8a13c24&rnd=29137126";
$new_host = "http://newhost.com/blab";
//explode at ? so you get the query
$split = explode("?",$url,2);
//build new url
$new_url = $new_host."?".$split[1];
//finish
echo $new_url;
The reverse function of parse_url() should be http_build_url(), have you tried with it?

Determining if a file DOES NOT exist

I have some code which seems logical but is not working as expected.
<?php
$ukip_code = "PTXC";
$show_logo = "http://www.ukipme.com/img/confs/" . strtolower($ukip_code) . ".gif";
echo $show_logo . "<br>";
echo "<img src=" . $show_logo . "><br>";
if (!file_exists($show_logo)) { // or file_exists($show_logo) === false
$show_logo = "http://placehold.it/165x100/&text={$ukip_code}";
}
echo $show_logo;
?>
My first echo shows the original file's URL. I then echo an img tag to prove that this file is an actual file.
I then check if the file exists, and if it does not, use a placeholder image. Echoing this variable now should give the original URL again (as it quite clearly does exist), but it gives the placeholder URL. Why?
I've also tried using file_exists($show_logo) === false in my if statement, but I get the same result.
You can use get_headers() method to get the status of the resource:
http://php.net/manual/en/function.get-headers.php
$regex = "(200|201|203|204|205|206)";
$headers = get_headers($show_logo);
preg_match($regex, $headers[0], $match);
if (!$match) {
$show_logo = "http://placehold.it/165x100/&text={$ukip_code}";
}
echo $show_logo;
You should use the server path to the site, not the url of the site. Something like /home/etc/file_name
Your var should be like this
$show_logo = "/{the site server path}/img/confs/" . strtolower($ukip_code) . ".gif";
if you need __FILE__ constant will give you absolute path to current file.
You can try to read in the contents which is behind the url. The drawback however is that this will generate some traffic for big images. But it makes sure that if the file can be downloaded from the given url that it is available. There is curl_setopt which could give you some more options.
<?php
$ukip_code = "PTXC";
$opt = FALSE;
$show_logo = "http://www.ukipme.com/img/confs/" . strtolower($ukip_code) . ".gif";
echo $show_logo . "<br>";
echo "<img src=" . $show_logo . "><br>";
// Create a curl session
$ch = curl_init($show_logo);
// Execution
curl_exec($ch);
// Verification if an error occured
if(!curl_errno($ch))
{
$info = curl_getinfo($ch, $opt);
}
// Fermeture du gestionnaire
curl_close($ch);
if ($opt === FALSE) {
$show_logo = "http://placehold.it/165x100/&text={$ukip_code}";
}
echo $show_logo;
?>
try something like this -
$file = $_SERVER['DOCUMENT_ROOT'].'sitepathtofile';
if (!file_exists($file)) {
set the placeholder
}

PHP combining multiple variable

I am new to php and I have a problem with the following code:
$ID = $_POST["first_name"]
$EXT = ".html"
$DOMAIN = "blabla.com/membersarea/"
$URL = ($DOMAIN . $ID . $EXT)
header("location: http://".$URL);
Here is the error I'm getting:
Parse error: syntax error, unexpected T_VARIABLE
The error is on line 3:
$EXT = ".html"
So my question is: is the error because of a point in a php variable?
You missed semicolon ; in your code. Each statements should ends with semi-colon ;
<?php
$ID = $_POST["first_name"];
$EXT = ".html";
$DOMAIN = "blabla.com/membersarea/";
$URL = ($DOMAIN . $ID . $EXT);
header("location: http://".$URL);
?>
You need to use ; semi-colon delimiter to say php that this is the end of this line...
<?php
$ID = $_POST["first_name"];
$EXT = ".html";
$DOMAIN = "blabla.com/membersarea/";
$URL = ($DOMAIN . $ID . $EXT);
header("location: http://".$URL);
?>
Also use exit; after header()
<?php
$ID = $_POST["first_name"]; /* Sanitize your data, atleast use mysqli_real_escape_string()*/
$EXT = ".html";
$DOMAIN = "blabla.com/membersarea/";
$URL = ($DOMAIN.$ID.$EXT); /* Also don't leave any spaces here */
header("location: http://".$URL);
exit;
?>
you have to put semi-colon at the end of each line to tell php its the end of line and you are going to start next one.
So, in your code put semi-colon(;) in the first four lines.

Get base directory of current script

This is the url of my script: localhost/do/index.php
I want a variable or a function that returns localhost/do (something like $_SERVER['SERVER_NAME'].'/do')
$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
Try:
$url = $_SERVER['REQUEST_URI']; //returns the current URL
$parts = explode('/',$url);
print_r($parts);
EDIT:
$url = $_SERVER['REQUEST_URI']; //returns the current URL
$parts = explode('/',$url);
$dir = $_SERVER['SERVER_NAME'];
for ($i = 0; $i < count($parts) - 1; $i++) {
$dir .= $parts[$i] . "/";
}
echo $dir;
This should return localhost/do/
I suggest not to use dirname(). I had several issues with multiple slashes and unexpected results at all. That was the reason why I created currentdir():
function currentdir($url) {
// note: anything without a scheme ("example.com", "example.com:80/", etc.) is a folder
// remove query (protection against "?url=http://example.com/")
if ($first_query = strpos($url, '?')) $url = substr($url, 0, $first_query);
// remove fragment (protection against "#http://example.com/")
if ($first_fragment = strpos($url, '#')) $url = substr($url, 0, $first_fragment);
// folder only
$last_slash = strrpos($url, '/');
if (!$last_slash) {
return '/';
}
// add ending slash to "http://example.com"
if (($first_colon = strpos($url, '://')) !== false && $first_colon + 2 == $last_slash) {
return $url . '/';
}
return substr($url, 0, $last_slash + 1);
}
Why you should not use dirname()
Assume you have image.jpg located in images/ and you have the following code:
<img src="<?php echo $url; ?>../image.jpg" />
Now assume that $url could contain different values:
http://example.com/index.php
http://example.com/images/
http://example.com/images//
http://example.com/
etc.
Whatever it contains, we need the current directory to produce a working deeplink. You try dirname() and face the following problems:
1.) Different results for files and directories
File
dirname('http://example.com/images/index.php') returns http://example.com/images
Directory
dirname('http://example.com/images/') returns http://example.com
But no problem. We could cover this by a trick:
dirname('http://example.com/images/' . '&') . '/'returns http://example.com/images/
Now dirname() returns in both cases the needed current directory. But we will have other problems:
2.) Some multiple slashes will be removed
dirname('http://example.com//images//index.php') returns http://example.com//images
Of course this URL is not well formed, but multiple slashes happen and we need to act like browsers as webmasters use them to verify their output. And maybe you wonder, but the first three images of the following example are all loaded.
<img src="http://example.com/images//../image.jpg" />
<img src="http://example.com/images//image.jpg" />
<img src="http://example.com/images/image.jpg" />
<img src="http://example.com/images/../image.jpg" />
Thats the reason why you should keep multiple slashes. Because dirname() removes only some multiple slashes I opened a bug ticket.
3.) Root URL does not return root directory
dirname('http://example.com') returns http:
dirname('http://example.com/') returns http:
4.) Root directory returns relative path
dirname('foo/bar') returns .
I would expect /.
5.) Wrong encoded URLs
dirname('foo/bar?url=http://example.com') returns foo/bar?url=http:
All test results:
http://www.programmierer-forum.de/aktuelles-verzeichnis-alternative-zu-dirname-t350590.htm#4329444
php has many functions for string parsing which can be done with simple one-line snippets
dirname() (which you asked for) and parse_url() (which you need) are among them
<?php
echo "Request uri is: ".$_SERVER['REQUEST_URI'];
echo "<br>";
$curdir = dirname($_SERVER['REQUEST_URI'])."/";
echo "Current dir is: ".$curdir;
echo "<br>";
address bar in browser is
http://localhost/do/index.php
output is
Request uri is: /do/index.php
Current dir is: /do/
When I was implementing some of these answers I hit a few problems as I'm using IIS and I also wanted a fully qualified URL with the protocol as well. I used PHP_SELF instead of REQUEST_URI as dirname('/do/') gives '/' (or '\') in Windows, when you want '/do/' to be returned.
if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off') {
$protocol = 'http://';
} else {
$protocol = 'https://';
}
$base_url = $protocol . $_SERVER['SERVER_NAME'] . dirname($_SERVER['PHP_SELF']);
If you want to include the server name, as I understood, then the following code snippets should do what you are asking for:
$result = $_SERVER['SERVER_NAME'] . dirname(__FILE__);
$result = $_SERVER['SERVER_NAME'] . __DIR__; // PHP 5.3
$result = $_SERVER['SERVER_NAME'] . '/' . dirname($_SERVER['REQUEST_URI']);
dirname will give you the directory portion of a file path. For example:
echo dirname('/path/to/file.txt'); // Outputs "/path/to"
Getting the URL of the current script is a little trickier, but $_SERVER['REQUEST_URI'] will return you the portion after the domain name (i.e. it would give you "/do/index.php").
the best way is to use the explode/implode function (built-in PHP) like so
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$parts = explode('/',$actual_link);
$parts[count($parts) - 1] = "";
$actual_link = implode('/',$parts);
echo $actual_link;
My Suggestion:
const DELIMITER_URL = '/';
$urlTop = explode(DELIMITER_URL, trim(input_filter(INPUT_SERVER,'REQUEST_URI'), DELIMITER_URL))[0]
Test:
const DELIMITER_URL = '/';
$testURL = "/top-dir";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test/";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test/this.html";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
$testURL = "/top-dir/test.html";
var_dump(explode(DELIMITER_URL, trim($testURL, DELIMITER_URL))[0]);
Test Output:
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
string(7) "top-dir"
A shorter (and correct) solution that keeps trailing slash:
$url = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$url_dir = preg_replace('/[^\/]+\.php(\?.*)?$/i', '', $url);
echo $url_dir;
My Contribution
Tested and worked
/**
* Get Directory URL
*/
function get_directory_url($file = null) {
$protocolizedURL = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$trailingslashURL= preg_replace('/[^\/]+\.php(\?.*)?$/i', '', $protocolizedURL);
return $trailingslashURL.str_replace($_SERVER['DOCUMENT_ROOT'], '', $file);
}
USAGE
Example 1:
<?php echo get_directory_ur('images/monkey.png'); ?>This will return http://localhost/go/images/monkey.png
Example 2:
<?php echo get_directory_ur(); ?>This will return http://localhost/go/

php fopen - name of file

I currently have:
<?php
if (isset($_POST["submitwrite"])) {
$handle = fopen("writetest.txt","w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
?>
However I need to adjust the filename to be dynamic, instead of 'writetest.txt' I would like it to be: username+pollname+time.txt taking the $_post variables.
I would also like to change the directory these files are stored in to /results.
Help please...
You mean doing something like this?
$filename = '/results/' . $_POST['username'] . '/' . $_POST['pollname'] . '/time.txt';
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
// etc...
Or am I not understanding you?
Edit
To address the issue BalusC pointed out, this is a more complete solution.
It makes sure the $_POST['username'] and $_POST['pollname'] values are valid, so they won't create an invalid or possibly harmful $filename.
<?php
$basedir = '/results';
$basename = 'time.txt';
// Get user and poll names
$username = $_POST['username'];
$pollname = $_POST['pollname'];
// Counteract the old magic_qutoes feature, if needed.
if(get_magic_quotes_gpc()) {
$username = stripslashes($username);
$pollname = stripslashes($pollname);
}
// Validate user and poll names.
$regexp = '/^[\w\d\_\-\. \']+$/iu';
if(!preg_match($regexp, $username) || !preg_match($regexp, $pollname)) {
echo 'Username or pollname is invalid. Aborting!';
}
else {
// Compile the complete file name
$filename = $basedir . '/' . $username . '/' . $pollname . '/' . $basename;
// Write to the file
if (isset($_POST["submitwrite"])) {
$handle = fopen($filename,"w+");
if ($handle) {
fwrite($handle, "Dan"."¬".$_POST["username"]."¬".$_POST["pollname"]."¬".$_POST["ans1"]."¬".$_POST["ans2"]."¬".$_POST["ans3"]."¬".time());
fclose($handle);
}
}
}
?>
fopen creates (at least tries) the file if it does not exist, so
$filename = $username . $pollname . $time . '.txt';
$handle = fopen($filename, 'w+');
will work fine.
By the way, w+ places the pointer at the beginning of the file. If the file already has some data, it will truncate it first. If you want to append data to the file, you may want to use 'a+'

Categories