I need to find the screen resolution of a users screen who visits my website?
You can't do it with pure PHP. You must do it with JavaScript. There are several articles written on how to do this.
Essentially, you can set a cookie or you can even do some Ajax to send the info to a PHP script. If you use jQuery, you can do it something like this:
jquery:
$(function() {
$.post('some_script.php', { width: screen.width, height:screen.height }, function(json) {
if(json.outcome == 'success') {
// do something with the knowledge possibly?
} else {
alert('Unable to let PHP know what the screen resolution is!');
}
},'json');
});
PHP (some_script.php)
<?php
// For instance, you can do something like this:
if(isset($_POST['width']) && isset($_POST['height'])) {
$_SESSION['screen_width'] = $_POST['width'];
$_SESSION['screen_height'] = $_POST['height'];
echo json_encode(array('outcome'=>'success'));
} else {
echo json_encode(array('outcome'=>'error','error'=>"Couldn't save dimension info"));
}
?>
All that is really basic but it should get you somewhere. Normally screen resolution is not what you really want though. You may be more interested in the size of the actual browser's view port since that is actually where the page is rendered...
Directly with PHP is not possible but...
I write this simple code to save screen resolution on a PHP session to use on an image gallery.
<?php
session_start();
if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
echo 'User resolution: ' . $_SESSION['screen_width'] . 'x' . $_SESSION['screen_height'];
} else if(isset($_REQUEST['width']) AND isset($_REQUEST['height'])) {
$_SESSION['screen_width'] = $_REQUEST['width'];
$_SESSION['screen_height'] = $_REQUEST['height'];
header('Location: ' . $_SERVER['PHP_SELF']);
} else {
echo '<script type="text/javascript">window.location = "' . $_SERVER['PHP_SELF'] . '?width="+screen.width+"&height="+screen.height;</script>';
}
?>
New Solution If you need to send another parameter in Get Method (by Guddu Modok)
<?php
session_start();
if(isset($_SESSION['screen_width']) AND isset($_SESSION['screen_height'])){
echo 'User resolution: ' . $_SESSION['screen_width'] . 'x' . $_SESSION['screen_height'];
print_r($_GET);
} else if(isset($_GET['width']) AND isset($_GET['height'])) {
$_SESSION['screen_width'] = $_GET['width'];
$_SESSION['screen_height'] = $_GET['height'];
$x=$_SERVER["REQUEST_URI"];
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['width']);
unset($params['height']);
$string = http_build_query($params);
$domain=$_SERVER['PHP_SELF']."?".$string;
header('Location: ' . $domain);
} else {
$x=$_SERVER["REQUEST_URI"];
$parsed = parse_url($x);
$query = $parsed['query'];
parse_str($query, $params);
unset($params['width']);
unset($params['height']);
$string = http_build_query($params);
$domain=$_SERVER['PHP_SELF']."?".$string;
echo '<script type="text/javascript">window.location = "' . $domain . '&width="+screen.width+"&height="+screen.height;</script>';
}
?>
PHP is a server side language - it's executed on the server only, and the resultant program output is sent to the client. As such, there's no "client screen" information available.
That said, you can have the client tell you what their screen resolution is via JavaScript. Write a small scriptlet to send you screen.width and screen.height - possibly via AJAX, or more likely with an initial "jump page" that finds it, then redirects to http://example.net/index.php?size=AxB
Though speaking as a user, I'd much prefer you to design a site to fluidly handle any screen resolution. I browse in different sized windows, mostly not maximized.
Easiest way
<?php
//-- you can modified it like you want
echo $width = "<script>document.write(screen.width);</script>";
echo $height = "<script>document.write(screen.height);</script>";
?>
I found using CSS inside my html inside my php did the trick for me.
<?php
echo '<h2 media="screen and (max-width: 480px)">';
echo 'My headline';
echo '</h2>';
echo '<h1 media="screen and (min-width: 481px)">';
echo 'My headline';
echo '</h1>';
?>
This will output a smaller sized headline if the screen is 480px or less.
So no need to pass any vars using JS or similar.
You can check it like below:
if(strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'mobile') || strstr(strtolower($_SERVER['HTTP_USER_AGENT']), 'android')) {
echo "mobile web browser!";
} else {
echo "web browser!";
}
This is a very simple process. Yes, you cannot get the width and height in PHP. It is true that JQuery can provide the screen's width and height. First go to https://github.com/carhartl/jquery-cookie and get jquery.cookie.js. Here is example using php to get the screen width and height:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="js/jquery.cookie.js"></script>
<script type=text/javascript>
function setScreenHWCookie() {
$.cookie('sw',screen.width);
$.cookie('sh',screen.height);
return true;
}
setScreenHWCookie();
</script>
</head>
<body>
<h1>Using jquery.cookie.js to store screen height and width</h1>
<?php
if(isset($_COOKIE['sw'])) { echo "Screen width: ".$_COOKIE['sw']."<br/>";}
if(isset($_COOKIE['sh'])) { echo "Screen height: ".$_COOKIE['sh']."<br/>";}
?>
</body>
</html>
I have a test that you can execute: http://rw-wrd.net/test.php
Use JavaScript (screen.width and screen.height IIRC, but I may be wrong, haven't done JS in a while). PHP cannot do it.
Fully Working Example
I couldn't find an actual working PHP example to "invisibly" (without URL parameters) return client screen size, and other properties, to server-side PHP, so I put this example together.
JS populates and submits a hidden form (scripted by PHP from an array of JS properties), POSTing to itself (the data now available in PHP) and returns the data in a table.
(Tested in "several" browsers.)
<!DOCTYPE html>
<html>
<head>
<title>*Client Info*</title>
<style>table,tr{border:2px solid gold;border-collapse:collapse;}td{padding:5px;}</style>
</head>
<body>
<?php
$clientProps=array('screen.width','screen.height','window.innerWidth','window.innerHeight',
'window.outerWidth','window.outerHeight','screen.colorDepth','screen.pixelDepth');
if(! isset($_POST['screenheight'])){
echo "Loading...<form method='POST' id='data' style='display:none'>";
foreach($clientProps as $p) { //create hidden form
echo "<input type='text' id='".str_replace('.','',$p)."' name='".str_replace('.','',$p)."'>";
}
echo "<input type='submit'></form>";
echo "<script>";
foreach($clientProps as $p) { //populate hidden form with screen/window info
echo "document.getElementById('" . str_replace('.','',$p) . "').value = $p;";
}
echo "document.forms.namedItem('data').submit();"; //submit form
echo "</script>";
}else{
echo "<table>";
foreach($clientProps as $p) { //create output table
echo "<tr><td>".ucwords(str_replace('.',' ',$p)).":</td><td>".$_POST[str_replace('.','',$p)]."</td></tr>";
}
echo "</table>";
}
?>
<script>
window.history.replaceState(null,null); //avoid form warning if user clicks refresh
</script>
</body>
</html>
The returned data is extract'd into variables. For example:
window.innerWidth is returned in $windowinnerWidth
You can try RESS (RESponsive design + Server side components), see this tutorial:
http://www.lukew.com/ff/entry.asp?1392
You can set window width in cookies using JS in front end and you can get it in PHP:
<script type="text/javascript">
document.cookie = 'window_width='+window.innerWidth+'; expires=Fri, 3 Aug 2901 20:47:11 UTC; path=/';
</script>
<?PHP
$_COOKIE['window_width'];
?>
I don't think you can detect the screen size purely with PHP but you can detect the user-agent..
<?php
if ( stristr($ua, "Mobile" )) {
$DEVICE_TYPE="MOBILE";
}
if (isset($DEVICE_TYPE) and $DEVICE_TYPE=="MOBILE") {
echo '<link rel="stylesheet" href="/css/mobile.css" />'
}
?>
Here's a link to a more detailed script: PHP Mobile Detect
Here is the Javascript Code: (index.php)
<script>
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/sqldb.php", true);
xhttp.send("screensize=",screen.width,screen.height);
</script>
Here is the PHP Code: (sqldb.php)
$data = $_POST['screensize'];
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$statement = $pdo->prepare("UPDATE users SET screen= :screen WHERE id = $userid");
$statement->execute(array('screen' => $data));
I hope that you know how to get the $userid from the Session,
and for that you need an Database with the Table called users, and an Table inside users called screen ;=)
Regards KSP
The only way is to use javascript, then get the javascript to post to it to your php(if you really need there res server side). This will however completly fall flat on its face, if they turn javascript off.
JS:
$.ajax({
url: "ajax.php",
type: "POST",
data: "width=" + $("body").width(),
success: function(msg) {
return true;
}
});
ajax.php
if(!empty($_POST['width']))
$width = (int)$_POST['width'];
This can be done easily using cookies. This method allows the page to check the stored cookie values against the screen height and width (or browser view port height and width values), and if they are different it will reset the cookie and reload the page. The code needs to allow for user preferences. If persistant cookies are turned off, use a session cookie. If that doesn't work you have to go with a default setting.
Javascript: Check if height & width cookie set
Javascript: If set, check if screen.height & screen.width (or whatever you want) matches the current value of the cookie
Javascript: If cookie not set or it does not match the current value, then:
a. Javascript: create persistent or session cookie named (e.g.) 'shw' to value of current screen.height & screen.width.
b. Javascript: redirect to SELF using window.location.reload(). When it reloads, it will skip the step 3.
PHP: $_COOKIE['shw'] contains values.
Continue with PHP
E.g., I am using some common cookie functions found on the web. Make sure setCookie returns the correct values.
I put this code immediately after the head tag. Obviously the function should be in a a source file.
<head>
<script src="/include/cookielib.js"></script>
<script type=text/javascript>
function setScreenHWCookie() {
// Function to set persistant (default) or session cookie with screen ht & width
// Returns true if cookie matches screen ht & width or if valid cookie created
// Returns false if cannot create a cookies.
var ok = getCookie( "shw");
var shw_value = screen.height+"px:"+screen.width+"px";
if ( ! ok || ok != shw_value ) {
var expires = 7 // days
var ok = setCookie( "shw", shw_value, expires)
if ( ok == "" ) {
// not possible to set persistent cookie
expires = 0
ok = setCookie( "shw", shw_value, expires)
if ( ok == "" ) return false // not possible to set session cookie
}
window.location.reload();
}
return true;
}
setScreenHWCookie();
</script>
....
<?php
if( isset($_COOKIE["shw"])) {
$hw_values = $_COOKIE["shw"];
}
PHP works only on server side, not on user host. Use JavaScript or jQuery to get this info and send via AJAX or URL (?x=1024&y=640).
The quick answer is no, then you are probably asking why can't I do that with php. OK here is a longer answer. PHP is a serverside scripting language and therefor has nothing to do with the type of a specific client. Then you might ask "why can I then get the browser agent from php?", thats because that information is sent with the initial HTTP headers upon request to the server. So if you want client information that's not sent with the HTTP header you must you a client scripting language like javascript.
For get the width screen or the height screen
1- Create a PHP file (getwidthscreen.php) and write the following commands in it
PHP (getwidthscreen.php)
<div id="widthscreenid"></div>
<script>
document.getElementById("widthscreenid").innerHTML=screen.width;
</script>
2- Get the width screen through a cURL session by the following commands
PHP (main.php)
$ch = curl_init( 'http://hostname/getwidthscreen.php' );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
$result = curl_exec( $ch );
print_r($result);
curl_close( $ch );
Well, I have another idea, thanks to which it is 90% possible in a very simple way using pure PHP. We will not immediately know the exact screen resolution, but we will find out whether the user is using a computer (higher resolution) or a phone (lower resolution) and thanks to this we will be able to load specific data.
Code example:
$user_agent = $_SERVER['HTTP_USER_AGENT'];
if (strpos($user_agent, 'Windows') !== false) {
//PC, high resolution
//*note for phone is: Windows Phone
} elseif (strpos($user_agent, 'Mac') !== false) {
//PC, high resolution
} else {
//mobile, small resolution
//Android, iOS, Windows Phone, Blackberry OS, Symbian OS, Bada OS, Firefox OS, WebOS, Tizen OS, KaiOS, Sailfish OS, Ubuntu Touch, HarmonyOS, EMUI, OxygenOS, One UI, Magic UI, ColorOS, MiUI, OxygenOS, ZenUI, LG UX, FunTouch OS, Flyme OS, OxygenOS, Samsung One UI, Android One, Android Go, Android TV, Android Auto, Fuchsia OS.
}
Then, a great solution to complete the verification is to throw a cookie and check the data using PHP.
//JS:
function setCookieResolution() {
// Get screen resolution
if (!getCookieValue("screen_resolution")) {
var screenResolution = window.screen.width + "x" + window.screen.height;
// Create cookie with resolution info
document.cookie = "screen_resolution=" + screenResolution + ";path=/";
}
}
setCookieResolution();
//PHP:
if (isset($_COOKIE["screen_resolution"])) {
$currentValue = $_COOKIE["screen_resolution"];//example: 1920x1080
$parts = explode("x", $currentValue);
if(count($parts) == 2 && is_numeric($parts[0]) && is_numeric($parts[1])) {
$width = (int)$parts[0];
$height = (int)$parts[1];
} else {
// handle error
}
}
In PHP there is no standard way to get this information. However, it is possible if you are using a 3rd party solution. 51Degrees device detector for PHP has the properties you need:
$_51d['ScreenPixelsHeight']
$_51d['ScreenPixelsWidth']
Gives you Width and Height of user's screen in pixels. In order to use these properties you need to download the detector from sourceforge. Then you need to include the following 2 lines in your file/files where it's necessary to detect screen height and width:
<?php
require_once 'path/to/core/51Degrees.php';
require_once 'path/to/core/51Degrees_usage.php';
?>
Where path/to/core is path to 'Core' directory which you downloaded from sourceforge. Finally, to use the properties:
<?php
echo $_51d['ScreenPixelsHeight']; //Output screen height.
echo $_51d['ScreenPixelsWidth']; //Output screen width.
?>
Keep in mind these variables can contain 'Unknown' value some times, when the device could not be identified.
solution: make scalable web design ... ( our should i say proper web design) formating should be done client side and i did wish the info would be passed down to server but the info is still usefull ( how many object per rows kind of deal ) but still web design should be fluid thus each row elements should not be put into tables unless its an actual table ( and the data will scale to it's individual cells) if you use a div you can stack each elements next to each other and your window should "break" the row at the proper spot. ( just need proper css)
<script type="text/javascript">
if(screen.width <= 699){
<?php $screen = 'mobile';?>
}else{
<?php $screen = 'default';?>
}
</script>
<?php echo $screen; ?>
Related
I'm trying to make a Chat App using HTML, CSS, JS, PHP and Mysql.
I've completed all the functionalities that includes sending a message, receiving a message, displaying users... But the issue i'm facing is that i need to refresh the page every time i received a new message.
I'm looking for a way to auto update data with new data from mysql database.
Code:
<?php
if ($_GET['id']){
$id = $_GET['id'];
$id = preg_replace("/[^0-9]/", "", $id);
$fetching_messages = "SELECT * FROM users_messages WHERE from_user='$id' OR to_user='$id' ORDER BY id";
$check_fetching_messages = $db->prepare($fetching_messages);
$check_fetching_messages->execute();
$messages_all = $check_fetching_messages->fetchAll();
} else {
}
?>
<div id="autodata">
<?php foreach($to_users as $to_user) : ?>
<?php
$to_user_id = $to_user['to_user'];
$to_user_name = "SELECT * FROM users_accounts WHERE id='$to_user_id'";
$check_to_user_name = $db->query($to_user_name);
while ($row_to_user_name = $check_to_user_name->fetch()) {
$id_user = $row_to_user_name['id'];
$username = $row_to_user_name['username'];
$pdp = $row_to_user_name['profile_image'];
}
if ($id_user == $user_id){
} else {
echo '
<form style="height: fit-content;" name="goto'.$to_user_id.'" action="inbox.php">
<div onclick="window.location.replace('."'".'?id='.$to_user_id."'".')" class="inbox_chat_field_user">';
if (empty($pdp)){
echo "<img class='inbox_chat_field_user_img' src='uploads\profile\default.jpg'/>";
} else {
echo "<img class='inbox_chat_field_user_img' src='".$pdp."'/>";
}
echo '
<span class="inbox_chat_field_user_p">'.$username.'</span>
</div>
</form>
<hr class="inbox_separing_hr">';
}
?>
<?php endforeach;?>
</div>
Simply you can't do that, PHP is a server-side language, you can't tell the clients to refresh from PHP.
To accomplish that chat you should consider JavaScript in the browser.
The easiest way is by sending an AJAX request to your server and check if there are new messages every 5 or 10 seconds, and then do what you want with the messages in the response.
If you use jquery in your application you can send ajax request in this way:
$.get( "messages.php", function( data ) {
console.log( "Data Loaded: " + data );
});
and in messages.php script, you can fetch new messages from the database and return them with HTML or JSON format
You may also use FCM service offered by firebase to push your messages to the client directly, Check this package for PHP FCM.
There are other solutions like websockets etc...
It would have been easier for me to directly update your code had you separated business logic from presentation, so I am not going to attempt to do that. Instead I will describe a technique you can use and leave it to you to figure out the best way to use it. You might consider using server-sent events. See the JavaScript class EventSource.
The following "business logic" PHP program, sse_cgi.php, periodically has new output every 2 seconds (for a total of 5 times). In this case the output is just the current date and time as a string. But it could be, for example, a JSON record. Note the special header that it outputs:
<?php
header("Content-Type: text/event-stream");
$firstTime = True;
for ($i = 0; $i < 5; $i++) {
if (connection_aborted()) {
break;
}
$curDate = date(DATE_ISO8601);
echo 'data: This is a message at time ' . $curDate, "\n\n";
// flush the output buffer and send echoed messages to the browser
while (ob_get_level() > 0) {
ob_end_flush();
}
flush();
if ($i < 4) {
sleep(2); # Sleep for 2 seconds
}
}
And this is the presentation HTML that would be outputted. JavaScript code in this case is just replacing the old date with the updated value. It could just as well append new <li> elements to an existing <ul> tag or <tr> elements to an existing <table>.
<html>
<head>
<meta charset="UTF-8">
<title>Server-sent events demo</title>
</head>
<body>
<div id='date'></div>
<script>
var evtSource = new EventSource('sse_cgi.php');
var date = document.getElementById('date');
evtSource.onmessage = function(e) {
// replace old content
date.innerHTML = e.data;
};
evtSource.onerror = function() {
// occurs when script terminates:
evtSource.close();
console.log('Done!');
};
</script>
</body>
</html>
Note that this presentation references the "business logic" scripts that returns the successive dates.
Important Note
It is important to realize that this technique keeps the connection to the server open for the duration until all the data has been ultimately sent and the business logic script ultimately terminates (or the presentation running in the browser issues a call to evtSource.close() to close the connection). So if you have a lot of simultaneous users, this could be an issue.
If your application does not have a limited number of messages to return then the previously described problem can be overcome by having the business logic script return immediately after having sent one message. This will break the connection with the browser, which if it is still there, will automatically attempt to re-connect with the business logic script (note that this reconnection can take a while):
Updated Business Logic
<?php
header("Content-Type: text/event-stream");
# Simulate waiting for next message:
sleep(2);
$curDate = date(DATE_ISO8601);
echo 'data: This is a message at time ' . $curDate, "\n\n";
// flush the output buffer and send echoed messages to the browser
while (ob_get_level() > 0) {
ob_end_flush();
}
flush();
Updated Presentation
<html>
<head>
<meta charset="UTF-8">
<title>Server-sent events demo</title>
</head>
<body>
<div id='date'></div>
<script>
var evtSource = new EventSource('sse_cgi.php');
var date = document.getElementById('date');
evtSource.onmessage = function(e) {
// replace old content
date.innerHTML = e.data;
};
</script>
</body>
</html>
I'm new in programming and API and I want to know how can I redirect to the URL sent by an API Response like below, please take note that the merchantURL changes everytime a customer submit new transaction.
decision = ACCEPT
reasonCode = 100
requestID = 5199043764236716204011
requestToken = AhjnrwSTGdc55dvfMd/rmBles0iRokq1GiOZKW+XDR/x6Q27g++QyaSZbpAcCSAkxnXOeXb3zHf6wAAAAQqe
apSaleReply->reasonCode = 100
apSaleReply->merchantURL = https://www.sofort.com/payment/go/3e54e5e50b5114f5c11ef40b2d45dbb7a4d808b3
This is how I requested the merchantURL:
printf( "apSaleReply->merchantURL = " . $reply->apSaleReply->merchantURL . "<br>");
and I have an IF statement that if the reason code is equal to 100 then it will redirect to the URL:
if ($reply->reasonCode == 100){
?>
<script>
window.location.href = "";
</script>
<?php
}
This is already working if I input any URL, I'm only stuck on how to get the value of the merchantURL since it is always changing and specify it in the window.location.href.
Hope you can help me out! Thank you in advance!
You can use php header
header("Location: " . $reply->apSaleReply->merchantUR );
Or you can alter your existing code as below to get this work
if ($reply->reasonCode == 100){
?>
<script>
window.location.href = "<?php echo $reply->apSaleReply->merchantUR; ?>";
</script>
<?php
}
What about this?
window.location.href = "<?= $reply->apSaleReply->merchantURL ?>";
(I assume your template and back-end code is in the same file, otherwise use a session data. Let me know if it's the case.)
I have an ipcamera from which /video/feed/1.jpg (mounted as a ramdrive) is being written to at approx 5fps. Sometimes this can be less than 1 fps if the connection is poor.
I'm trying to update the image in a browser every 500ms but i have two goals:
I don't want the server to output the same image if it has not been updated by the camera.
I dont want to output a partial image if the camera had not finished writing it yet.
I tried to achieve this by creating an md5 of the image and storing it in the session, if on the next browser request the md5 is unchanged, the server loops until the md5 is different. The server will also loop until the md5 matches the previous time it was loaded, this way I can be sure that the camera had finished creating the image.
The process works as expected but the cpu usage goes through the roof, so I'm looking for suggestions on improvements.
test.php
<?php
session_start();
$imgFile = '/video/feed/1.jpg';
$lastImg = $_SESSION['image'];
$imgMd5 =0;
do {
sleep(.2);
$img = (file_get_contents($imgFile));
$lastMd5 = $imgMd5;
$imgMd5 = md5($img);
if ($lastMd5 != $imgMd5) {
continue;
}
if ($imgMd5 != $lastImg) {
break;
}
} while (0 == 0);
header("Content-type: image/jpg");
$_SESSION['image'] = md5($img);
echo $img;
exit;
?>
JS
<script>
img = new Image
function f() {
img.src = "test.php?rnd=" + Date.now();
img.onload = function() {
feed.src = img.src;
setTimeout(function() {
f();
}, 500);
};
img.onerror= function(){
setTimeout(function() {
f();
}, 500);
};
}
f();
</script>
What I really needed was usleep(200000)
sleep(.2) did not work as I expected.
Instead of using an MD5 hash to check if the file changed, use the last modified time which should be less resource-intensive than computing an MD5 hash each time (but for some reason on my Windows machine it still uses a lot of CPU so I'm not sure), you can try my code :
<?php
session_start();
$path = "/video/feed/1.jpg";
if (isset($_SESSION["lastmodified"])) { // if there's no previous timestamp, do not execute all of this and jump straight into serving the image.
while ($_SESSION["lastmodified"] == filemtime($path)) {
sleep(1); // sleep while timestamp is the same as before.
clearstatcache(); // PHP caches file informations such as last modified timestamp, so we need to clear it each time or we'll run into an infinite loop.
}
}
$_SESSION["lastmodified"] = filemtime($path); // set the new time variable.
header("Content-type: image/jpg");
echo file_get_contents($path);
?>
Edit: you can just let your webserver handle all of this by directly serving the RAMdisk directory, setting appropriate cache-control headers and using a meta refresh tag to reload the page every second. When the page reloads, the webserver will serve a new image only if it exists (and if not, it'll just return "not modified" to the browser and it'll serve the last image from its cache).
I've never delt with sound clips and im wanting to play one via an event.
I have a file which has a snippet like so:
if( $get['0002'] == 'mu' ) {
switch( $get['0000'] ) {
case 'mp3': header('Content-Type: audio/mp3'); break;
case 'wav': header('Content-Type: audio/x-wav'); break;
default: break;
}
echo file_get_contents('./folder-name/' . $get['0001'] . '.' . $get['0000'] );
exit;
}
and on the page I fave this button;
<input type="button" value="Play Sound" onClick="EvalSound('sound1')" >
and this hidden away in the background
<embed src="./?0000=wav&0001=0001&0002=mu" autostart=false width=0 height=0 id="sound1" enablejavascript="true">
and the js being;
<script>
function EvalSound(soundobj) {
var thissound=document.getElementById(soundobj);
thissound.Play();
}
</script>
This does not seem to work and I believe it has something to do with the PHP headers. Could someone please point me in the right direction, as it would be much appreciated.
Please do some testing here with: http://www.phon.ucl.ac.uk/home/mark/audio/play.htm
On firefox I get an error for the Play() function.
Use something like firebug to give you more information.
If everything works then start debugging your php script.
I have got this JavaScript code for uploading files to my server (named it "upload.js"):
function startUpload(){
document.getElementById('upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is [HERE I NEED THE VARIABLE FROM THE EXTERNAL PHP FILE]!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
And I've got a simple .php file that process uploads with renaming the uploaded files (I named it "process_file.php"), and connects again with upload.js to fetch the result:
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit = rand(0000,9999);
$new_file_name = $random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>
What I need is inside upload.js to visualize the new name of the uploaded file as an answer if the upload process has been correct? I wrote inside JavaScript code above where exactly I need to put the new name answer.
You have to change your code to the following.
<?php
$file_name = $HTTP_POST_FILES['myfile']['name'];
$random_digit=rand(0000,9999);
$new_file_name=$random_digit.$file_name;
$path= "../../../images/home/smsbanner/pixels/".$new_file_name;
if($myfile !=none)
{
if(copy($HTTP_POST_FILES['myfile']['tmp_name'], $path))
{
$result = 1;
}
else
{
$result = 0;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo "message" ?>');</script>
And your JavaScript code,
function stopUpload(success, message){
var result = '';
if (success == 1){
result = '<div class="correct_sms">The file name is '+message+'!</div>';
}
else {
result = '<div class="wrong_sms">There was an error during upload!</div>';
}
document.getElementById('upload_form').innerHTML = result;
document.getElementById('upload_form').style.visibility = 'visible';
return true;
}
RageZ's answer was just about what I was going to post, but to be a little more specific, the last line of your php file should look like this:
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>, '<?php echo $new_file_name ?>');</script>
The javascript will error without quotes around that second argument and I'm assuming $new_file_name is what you want to pass in. To be safe, you probably even want to escape the file name (I think in this case addslashes will work).
A dumb man once said; "There are no stupid questions, only stupid answers". Though he was wrong; there are in fact loads of stupid questions, but this is not one of them.
Besides that, you are stating that the .js is uploading the file. This isn't really true.
I bet you didn't post all your code.
You can make the PHP and JavaScript work together on this problem by using Ajax, I recommend using the jQuery framework to accomplish this, mostly because it has easy to use functions for Ajax, but also because it has excellent documentation.
How about extending the callback script with:
window.top.window.stopUpload(
<?php echo $result; ?>,
'<?php echo(addslashes($new_file_name)); ?>'
);
(The addslashes and quotes are necessary to make the PHP string come out encoded into a JavaScript string literal.)
Then add a 'filename' parameter to the stopUpload() function and spit it out in the HTML.
$new_file_name=$random_digit.$file_name;
Sorry, that is not sufficient to make a filename safe. $file_name might contain segments like ‘x/../../y’, or various other illegal or inconsistently-supported characters. Filename sanitisation is much harder than it looks; you are better off making up a completely new (random) file name and not relying on user input for it at all.