Determining if a file DOES NOT exist - php

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
}

Related

I am trying to download a file from mysql, I saved the file location in the database, now I am trying to make a download link for the user on my page

Unable to create the download link. I am fetching the path saved from database and then try to make a link for it to download, but nothing happens.
Below is my code:
$query_print="SELECT vitae_pi FROM pi WHERE username='t124'";
$query_print_run=mysqli_query($conn,$query_print);
$query_print_recordset=mysqli_fetch_assoc($query_print_run);
$query_print_path=$query_print_recordset['vitae_pi'];
echo ' this is file path '.$query_print_path;
Here I am simply trying to create the download link for user t124, instead of using the current user for testing purposes?
This is hyperlink code:
<?php echo "<a href='".$query_print_path."'>".DOWNLOAD."</a>"; ?>
Any suggestions?
This my move file function:
protected function moveFile($file)
{
$filename = isset($this->newName) ? $this->newName : $file['name'];
//echo $filename;
$success = move_uploaded_file($file['tmp_name'], $this->destination . $filename);
if ($success) {
$result = $file['name'] . ' was uploaded successfully';
if (!is_null($this->newName)) {
$_SESSION['current_filename']=$this->newName;
echo $_SESSION['current_filename'];
$result .= ', and was renamed ' . $this->newName;
}
else{
$_SESSION['current_filename']=$file['name'];
echo $_SESSION['current_filename'];
}
//$result .= '.';
//echo $this->newName;
$this->messages[] = $result;
} else {
$this->messages[] = 'Could not upload ' . $file['name'];
}
}
Updating the table with file path:
$file_path_variable1= $destination1.$_SESSION['current_filename'];
echo '$file_path_variable1 : '.$file_path_variable1;
$query1="UPDATE proposal SET whitepaper_prop='$file_path_variable1' WHERE userName_prop='$currentuser'";
$result_query1=mysqli_query($conn,$query1);
....................
SOLUTION CODE IS:
Solution code is :
$query_print="SELECT vitae_pi FROM pi WHERE username='t115'";
$query_print_run=mysqli_query($conn,$query_print);
$query_print_recordset=mysqli_fetch_assoc($query_print_run);
$query_print_path=$query_print_recordset['vitae_pi'];
$dir= 'uploaded/';
$path=opendir($dir);
<?php
}while($query_pi_array=mysqli_fetch_assoc($query_pi_result));?>
<div>
<?php while($file=readdir($path)){
if($file != "." || $file !=".."){
if($file==$query_print_path){ ?>
Proposal Whitepaper
What does this display ?
<?php echo "<a href='".$query_print_path."'>".DOWNLOAD."</a>"; ?>
DOWNLOAD should be part of the PHP string, if not, it will be considered as a constant :
<?php echo "<a href='".$query_print_path."'>DOWNLOAD</a>"; ?>
Also, use double quotes for HTML attributes :
<?php echo "DOWNLOAD"; ?>
And the optimized way (to avoid useless string parsing) :
<?php echo 'DOWNLOAD'; ?>

Checking if file exists

I have a piece of code that checks whether an image exists in the file system and if so, displays it.
if (file_exists(realpath(dirname(__FILE__) . $user_image))) {
echo '<img src="'.$user_image.'" />';
}
else {
echo "no image set";
}
If I echo $user_image out, copy and paste the link into the browser, the image is there.
However, here, the 'no image set' is always being reached.
The $user_image contents are http://localhost:8888/mvc/images/users/1.jpg
Some of these functions not needed?
Any ideas?
Broken code or a better way of doing it (that works!)?
Beside #hek2mgl answer which i think is correct, i also think you should switch to is_file() instead of file_exists().
Also, you can go a bit further like:
if(is_file(dirname(__FILE__). '/' . $user_image) && false !== #getimagesize(dirname(__FILE__) . '/'. $user_image)) {
// image is fine
} else {
// it isn't
}
L.E:1
Oh great, now you are telling us what $user_image contains? Couldn't you do it from the start, could you?
So you will have to:
$userImagePath = parse_url($user_image, PHP_URL_PATH);
$fullPath = dirname(__FILE__) . ' / ' . $userImagePath;
if($userImagePath && is_file($fullPath) && false !== #getimagesize($fullPath)) {
// is valid
}else {
// it isn't
}
L.E: 2
Also, storing the entire url is not a good practice, what happens when you switch domain names? Try to store only the relative path, like /blah/images/image.png instead of http://locathost/blah/images/image.png
You missed the directory separator / between path and filename. Add it:
if (file_exists(realpath(dirname(__FILE__) . '/' . $user_image))) {
Note that dirname() will return the directory without a / at the end.

PHP variable with Javascript

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>

Replace string before a string?

Sorry, I'm bad English. I'm going to post my code now:
$image = 'http://example.com/thisisimage.gif';
$filename = substr($image, strrpos($image, '/') + 1);
echo '<br>';
echo $filename;
echo '<br>';
echo preg_replace('/^[^\/]+/', 'http://mydomain.com', $image);
echo '<br>';
$image is string;
$filename is image name (in example above, it returns 'thisisimage.gif')
Now i want replace all before $filename with 'http://mydomain.com', my code is above but it doesnt work.
Thanks!
$foo = explode($filename, $image);
echo $foo[0];
Explode "splits" one the given paramater ( in your case $filename ). It returns an array with where the keys are split on the string you gave.
And if you just want to change the url. you use a str_replace
$foo = str_replace("http://example.com", "http://localhost", $image);
//This will change "http://example.com" to "http://localhost", like a text replace in notepad.
In your case:
$image = 'http://example.com/thisisimage.gif';
$filename = substr($image, strrpos($image, '/') + 1);
$foo = explode($filename, $image);
echo '<br>';
echo $filename;
echo '<br>';
echo str_replace($foo[0], "http://yourdomain.com/", $url);
echo '<br>';
There's another approach in which you don't need a regular expression:
in Short:
$image = 'http://example.com/thisisimage.gif';
$url = "http://mydomain.com/".basename($image);
Explanation:
If you just want the file name without url's or directory path's, basename() is your friend;
$image = 'http://example.com/thisisimage.gif';
$filename = basename($image);
output: thisisimage.gif
Then you can add whatever domain you want:
$mydomain = "http://mydomain.com/";
$url = $mydomain.$filename;
Try this :
$image = 'http://example.com/thisisimage.gif';
echo preg_replace('/^http:\/\/.*\.com/', 'http://mydomain.com',$image);
This should simply work:
$image = 'http://example.com/thisisimage.gif';
$filename = substr($image, strrpos($image, '/') + 1);
echo '<br>';
echo $filename;
echo '<br>';
echo 'http://mydomain.com/'.$filename;
echo '<br>';
if you just like to add your own domain before the file name, try this:
$filename = array_pop(explode("/", $image));
echo "http://mydomain.com/" . $filename;
if you wanna only replace thedomain, try this:
echo preg_replace('/.*?[^\/]\/(?!\/)/', 'http://mydomain.com/', $image);
The other people here have given good answers about how to do it - regex has its advantages but also drawbacks - its slower, respectively requires more resources and for something simple as this, I would advice you to use the explode approach, but while speaking for regex functions you also may try this, instead your preg_replace:
echo preg_replace('#(?:.*?)/([^/]+)$#i', 'http://localhost/$1', $image);
It seems variable length positve lookbehind is not supported in PHP.

Selenium2 firefox: use the default profile

Selenium2, by default, starts firefox with a fresh profile. I like that for a default, but for some good reasons (access to my bookmarks, saved passwords, use my add-ons, etc.) I want to start with my default profile.
There is supposed to be a property controlling this but I think the docs are out of sync with the source, because as far as I can tell webdriver.firefox.bin is the only one that works. E.g. starting selenium with:
java -jar selenium-server-standalone-2.5.0.jar -Dwebdriver.firefox.bin=not-there
works (i.e. it complains). But this has no effect:
java -jar selenium-server-standalone-2.5.0.jar -Dwebdriver.firefox.profile=default
("default" is the name in profiles.ini, but I've also tried with "Profile0" which is the name of the section in profiles.ini).
I'm using PHPWebdriver (which uses JsonWireProtocol) to access:
$webdriver = new WebDriver("localhost", "4444");
$webdriver->connect("firefox");
I tried doing it from the PHP side:
$webdriver->connect("firefox","",array('profile'=>'default') );
or:
$webdriver->connect("firefox","",array('profile'=>'Profile0') );
with no success (firefox starts, but not using my profile).
I also tried the hacker's approach of creating a batch file:
#!/bin/bash
/usr/bin/firefox -P default
And then starting Selenium with:
java -jar selenium-server-standalone-2.5.0.jar -Dwebdriver.firefox.bin="/usr/local/src/selenium/myfirefox"
Firefox starts, but not using by default profile and, worse, everything hangs: selenium does not seem able to communicate with firefox when started this way.
P.S. I saw Selenium - Custom Firefox profile I tried this:
java -jar selenium-server-standalone-2.5.0.jar -firefoxProfileTemplate "not-there"
And it refuses to run! Excited, thinking I might be on to something, I tried:
java -jar selenium-server-standalone-2.5.0.jar -firefoxProfileTemplate /path/to/0abczyxw.default/
This does nothing. I.e. it still starts with a new profile :-(
Simon Stewart answered this on the mailing list for me.
To summarize his reply: you take your firefox profile, zip it up (zip, not tgz), base64-encode it, then send the whole thing as a /session json request (put the base64 string in the firefox_profile key of the Capabilities object).
An example way to do this on Linux:
cd /your/profile
zip -r profile *
base64 profile.zip > profile.zip.b64
And then if you're using PHPWebDriver when connecting do:
$webdriver->connect("firefox", "", array("firefox_profile" => file_get_contents("/your/profile/profile.zip.b64")))
NOTE: It still won't be my real profile, rather a copy of it. So bookmarks won't be remembered, the cache won't be filled, etc.
Here is the Java equivalent. I am sure there is something similar available in php.
ProfilesIni profile = new ProfilesIni();
FirefoxProfile ffprofile = profile.getProfile("default");
WebDriver driver = new FirefoxDriver(ffprofile);
If you want to additonal extensions you can do something like this as well.
ProfilesIni profile = new ProfilesIni();
FirefoxProfile ffprofile = profile.getProfile("default");
ffprofile.addExtension(new File("path/to/my/firebug.xpi"));
WebDriver driver = new FirefoxDriver(ffprofile);
java -jar selenium-server-standalone-2.21.0.jar -Dwebdriver.firefox.profile=default
should work. the bug is fixed.
Just update your selenium-server.
I was curious about this as well and what I got to work was very simple.
I use the command /Applications/Firefox.app/Contents/MacOS/firefox-bin -P to bring up Profile Manager. After I found which profile I needed to use I used the following code to activate the profile browser = Selenium::WebDriver.for :firefox, :profile => "batman".
This pulled all of my bookmarks and plug-ins that were associated with that profile.
Hope this helps.
From my understanding, it is not possible to use the -Dwebdriver.firefox.profile=<name> command line parameter since it will not be taken into account in your use case because of the current code design. Since I faced the same issue and did not want to upload a profile directory every time a new session is created, I've implemented this patch that introduces a new firefox_profile_name parameter that can be used in the JSON capabilities to target a specific Firefox profile on the remote server. Hope this helps.
I did It in Zend like this:
public function indexAction(){
$appdata = 'C:\Users\randomname\AppData\Roaming\Mozilla\Firefox' . "\\";
$temp = 'C:\Temp\\';
$hash = md5(rand(0, 999999999999999999));
if(!isset($this->params['p'])){
shell_exec("\"C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe\" -CreateProfile " . $hash);
}else{
$hash = $this->params['p'];
}
$ini = new Zend_Config_Ini('C:\Users\randomname\AppData\Roaming\Mozilla\Firefox\profiles.ini');
$path = false;
foreach ($ini as $key => $value){
if(isset($value->Name) && $value->Name == $hash){
$path = $value->Path;
break;
}
}
if($path === false){
die('<pre>No profile found with name: ' . $hash);
}
echo "<pre>Profile : $hash \nProfile Path : " . $appdata . "$path \n";
echo "Files: \n";
$filesAndDirs = $this->getAllFiles($appdata . $path);
$files = $filesAndDirs[0];
foreach ($files as $file){
echo " $file\n";
}
echo "Dirs : \n";
$dirs = array_reverse($filesAndDirs[1]);
foreach ($dirs as $dir){
echo " $dir\n";
}
echo 'Zipping : ';
$zip = new ZipArchive();
$zipPath = md5($path) . ".temp.zip";
$zipRet = $zip->open($temp .$zipPath, ZipArchive::CREATE);
echo ($zipRet === true)?"Succes\n":"Error $zipRet\n";
echo "Zip name : $zipPath\n";
foreach ($dirs as $dir){
$zipRet = $zip->addEmptyDir($dir);
if(!($zipRet === true) ){
echo "Error creating folder: $dir\n";
}
}
foreach ($files as $file){
$zipRet = $zip->addFile($appdata . $path ."\\". $file,$file);
if(!($zipRet === true && file_exists($appdata . $path . "\\". $file) && is_readable($appdata . $path . "\\". $file))){
echo "Error zipping file: $appdata$path/$file\n";
}
}
$zipRet = $zip->addFile($appdata . $path ."\\prefs.js",'user.js');
if(!($zipRet === true && file_exists($appdata . $path . "\\". $file) && is_readable($appdata . $path . "\\". $file))){
echo "Error zipping file: $appdata$path/$file\n";
}
$zipRet = $zip->close();
echo "Closing zip : " . (($zipRet === true)?("Succes\n"):("Error:\n"));
if($zipRet !== true){
var_dump($zipRet);
}
echo "Reading zip in string\n";
$zipString = file_get_contents($temp .$zipPath);
echo "Encoding zip\n";
$zipString = base64_encode($zipString);
echo $zipString . "\n";
require 'webdriver.php';
echo "Connecting Selenium\n";
$webDriver = new WebDriver("localhost",'4444');
if(!$webDriver->connect("firefox","",array('firefox_profile'=>$zipString))
{
die('Selenium is not running');
}
}
private function getAllFiles($path,$WithPath = false){
$return = array();
$dirs = array();
if (is_dir($path)) {
if ($dh = opendir($path)) {
while (($file = readdir($dh)) !== false) {
if(!in_array($file, array('.','..'))){
if(is_dir($path . "\\" . $file)){
$returned = $this->getAllFiles($path . "\\" . $file,(($WithPath==false)?'':$WithPath) . $file . "\\");
$return = array_merge($return,$returned[0]);
$dirs = array_merge($dirs,$returned[1]);
$dirs[] = (($WithPath==false)?'':$WithPath) . $file;
}else{
$return[] = (($WithPath==false)?'':$WithPath) . $file;
}
}
}
closedir($dh);
}
}
return array($return,$dirs);
}
The Idea is that you give in the get/post/zend parameters P with the name of the profile if not a random wil be created, and he will zip all the files put it in the temp folder and put it in.

Categories